There are lots of variations of this question, many with REALLY long non-applicable details. Consider the following in a globals.ts
interestingString:string = 'blah';
now in a neighboring component neighbor.ts
displayMsg:string = this.formatInterestingStrs(this.globals.interestingString);
formatInterestingStrs(val:string) {
return val.substr(0, 21) + "...";
}
and in the HTML...
<div> here's the first 21 chars of something interesting: {{displayMsg}} </div>
lastly... any other component can update the string at any time...
this.globals.interestingString = "I saw Cher in real life today! Man, did she dish on Greg Allman!"
I COULD solve this by writing the HTML as ...
<div> here's the first 21 chars of something interesting: {{this.formatInterestingStrs(this.globals.interestingString)}} </div>
...but the performance suffers. What I would like to be able to do is "easily" make the globals variable observable or published when changed AND have each use of it subscribe to the changes and THEN call a function to make any additional modifications that depend on its value. Something like in the globals...
PublishUpdates(interestingString:string = 'blah');
and in the module...
SubscribeToUpdates(this.globals.interestingString).thenDoThis(result){
this.displayMsg = this.formatInterestingStrs(result);
}
...and I'd like to do it without adding bloatware or tons of additional code and steps. Any ideas?
Finally spent the day researching this. You want to use multicast observables from RxJS. It's very efficient code and should be native to your Angular app.
For the above example, in the globals.ts file, add...
import { Observable, Subject } from 'rxjs';
public interestingString:string = 'blah';
public updateString$ = Observable.create((observer) => {
observer.next(this.interestingString);
});
public interestingString$ = new Subject();
Now, in as many component .ts files as you like, add this...
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 next step can be in any other module or this one... like maybe later as a click event on a button; when you want to change the value so that all the subscribers update at once...
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$);