'Angular 2 Component listen to change in service

I've a simple question about change detection.

I have a component and a (global) service with a boolean inside. How can I make the component listen to that boolean and execute a function if that boolean changes?

Thanks!



Solution 1:[1]

The Sam's answer is completely right. I would just want to add that you could also leverage a TypeScript setter to automatically trigger the event for changes:

@Injectable()
export class MyBooleanService {
    myBool$: Observable<boolean>;

    private boolSubject: Subject<boolean>;
    private _myBool: Boolean;

    constructor() {
        this.boolSubject = new Subject<boolean>();
        this.myBool$ = this.boolSubject.asObservable();
    }

    set myBool(newValue) {
      this._myBool = newValue;
      this.boolSubject.next(newValue);
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mwiza