Reputation: 34593
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.
Upvotes: 3
Views: 3555
Reputation: 34593
My application has several sub-modules, and a shared module to register common components, and modules between them. I had registered the ModalService
in the shared component.
I moved the ModalService to the Providers of the uppermost (app.module.ts) providers array, and it works as expected.
Thanks to @camaron for the tip. Note to self: never, ever register a provider in a shared module :)
Upvotes: 7