I am trying to create a common service for communication between components using Observable using: http://blog.angular-university.io/how-to-build-angular2-apps-using-rxjs-observable-data-services-pitfalls-to -avoid / as a guide:
import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; @Injectable() export class ModalService { private _isOpen: BehaviorSubject<boolean> = new BehaviorSubject(false); public isOpen: Observable<boolean> = this._isOpen.asObservable(); openModal() { this._isOpen.next(true); } closeModal() { this._isOpen.next(false); } }
in my component (s), I subscribe to isOpen , which gets the value when subscribing:
. . . ngOnInit(): void { this.subscription = this.modalService.isOpen.subscribe(state => { console.log('`isOpen` in subscription', state); }); }
However, when I run .openModal() on a shared service instance, the subscriber never gets a new value. What am I doing wrong?
My logic was that using the topic "Behavior" the subscriber received the initial value false , then I could change the value when I click on other components that have an instance of the shared service.
source share