Angular 2 Component listen to change in service

Han Che picture Han Che · Mar 28, 2016 · Viewed 22.5k times · Source

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!

Answer

Sam Storie picture Sam Storie · Mar 28, 2016

Depending on how that boolean changes you could expose it as an Observable<boolean> on your service, and then subscribe to that stream in your component. Your service would look something like:

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

    private boolSubject: Subject<boolean>;

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

    ...some code that emits new values using this.boolSubject...
}

Then in your component you would have something like this:

@Component({...})
export class MyComponent {
    currentBool: boolean;

    constructor(service: MyBooleanService) {
        service.myBool$.subscribe((newBool: boolean) => { this.currentBool = newBool; });
    }
}

Now depending on what you need to do with that bool value you may need to do some other things to get your component to update, but this is the gist of using an observable. Note, you will want to unsubscribe from the myBool$ stream at some point to prevent memory leaks and unexpected side effects.

Another option is you use the async pipe within your template instead of explicitly subscribing to the stream in the constructor. That will also ensure the subscription is disposed of automatically. Again though, that depends on what exactly you need to do with the bool values.