Subscriber does not get value from .next ()

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.

0
source share
1 answer

My application has several submodules and a common module for registering common components and modules between them. I registered ModalService in a common component.

I moved ModalService to Providers of the topmost provider (app.module.ts) provider, and it works as expected.

Thanks to @camaron for the tip. Note to yourself: never, never register a provider in a shared module :)

0
source

Source: https://habr.com/ru/post/1263347/


All Articles