Using an Observable to detect a change in a variable
Normally I would have my observables in services that get subscribed to in components, but I bundled them all in one class for the convenience of this answer. I've listed comments explaining each step. I hope this helps. : )
import { Subject } from 'rxjs/Subject';
export class ClassName {
// ------ Creating the observable ----------
// Create a subject - The thing that will be watched by the observable
public stringVar = new Subject<string>();
// Create an observable to watch the subject and send out a stream of updates (You will subscribe to this to get the update stream)
public stringVar$ = this.stringVar.asObservable() //Has a $
// ------ Getting Your updates ----------
// Subscribe to the observable you created.. data will be updated each time there is a change to Subject
public subscription = this.stringVar$.subscribe(data => {
// do stuff with data
// e.g. this.property = data
});
// ------ How to update the subject ---------
// Create a method that allows you to update the subject being watched by observable
public updateStringSubject(newStringVar: string) {
this.stringVar.next(newStringVar);
}
// Update it by calling the method..
// updateStringSubject('some new string value')
// ------- Be responsible and unsubscribe before you destory your component to save memory ------
ngOnDestroy() {
this.subscription.unsubscribe()
}
}