I'm trying to create a shared service to communicate between components using an 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 receives a value when subscribing:
. . .
ngOnInit(): void {
this.subscription = this.modalService.isOpen.subscribe(state => {
console.log('`isOpen` in subscription', state);
});
}
However, when I trigger .openModal()
on the shared service instance, the subscriber never receives the new value. What am I doing wrong?
My logic was that by using a Behavior Subject, the subscriber would receive an initial value of false
, then I could change the value on click from other components that have an instance of the shared service.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…