当变量更改值时,Angular 9调用函数

问题描述

此问题有很多变体,其中许多细节都非常长。在globals.ts

中考虑以下内容
this.$refs.msgs.$children[0].$children[0].removeItem()

现在在相邻组件neighbor.ts

interestingString:string = 'blah';

和HTML ...

displayMsg:string = this.formatInterestingStrs(this.globals.interestingString);

formatInterestingStrs(val:string) {
     return val.substr(0,21) + "...";
}

最后...任何其他组件都可以随时更新字符串...

<div> here's the first 21 chars of something interesting: {{displayMsg}} </div>

可以通过将HTML编写为...来解决此问题...

this.globals.interestingString = "I saw Cher in real life today! Man,did she dish on Greg Allman!"

...但是性能会下降。我想做的是“轻松”地使globals变量在更改时可以观察或发布,并让每次使用它都订阅更改,然后调用一个函数进行任何其他修改,具体取决于它的值。像是全局变量中的东西...

<div> here's the first 21 chars of something interesting: {{this.formatInterestingStrs(this.globals.interestingString)}} </div>

并在模块中...

PublishUpdates(interestingString:string = 'blah');

...而且我想这样做而不添加bloatware或大量其他代码和步骤。有什么想法吗?

解决方法

最后花了一天的时间对此进行研究。您想使用RxJS中的多播可观察对象。这是非常有效的代码,应该是您的Angular应用程序固有的。

对于上面的示例,在globals.ts文件中,添加...

import { Observable,Subject } from 'rxjs';

  public interestingString:string = 'blah';

  public updateString$ = Observable.create((observer) => {
    observer.next(this.interestingString);
  });

  public interestingString$ = new Subject();

现在,在任意数量的.ts组件文件中,添加此...

ngOnInit(): void {

    this.globals.interestingString$.subscribe((data) => {
      console.log('interestingString$: ' + data);
      //do whatever else you want to do when the interestingString changes
    });
    //...all your other code
}

下一步可以在任何其他模块中,也可以在其他任何模块中……就像稍后在按钮上单击事件一样;当您想要更改值以便所有订户立即更新...

this.globals.interestingString = "I saw Cher in real life today! Man,did she dish on Greg Allman!";
//updateProfile will automatically .next the current profile
// ...and then will push to all subscribers of profile$
this.globals.updateString$.subscribe(this.globals.interestingString$);