Angular9 当变量改变值时调用函数

Angular 9 call a function when a variable changes value

这个问题有很多变体,很多都有非常长的不适用细节。在 globals.ts

中考虑以下内容
interestingString:string = 'blah';

现在在邻近的组件中 neighbor.ts

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

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

并在 HTML...

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

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

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

可以通过将HTML写成...

来解决这个问题
<div> here's the first 21 chars of something interesting: {{this.formatInterestingStrs(this.globals.interestingString)}} </div>

...但性能受到影响。我希望能够做的是“轻松地”使全局变量在更改时可观察或发布,并且每次使用它都订阅更改,然后调用一个函数来根据其值进行任何其他修改。类似于全局变量...

PublishUpdates(interestingString:string = 'blah');

并在模块中...

SubscribeToUpdates(this.globals.interestingString).thenDoThis(result){
     this.displayMsg = this.formatInterestingStrs(result);
}

...而且我想在不添加过时软件或大量额外代码和步骤的情况下完成此操作。有什么想法吗?

终于花了一天时间研究这个。你想使用来自 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$);