Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
739 views
in Technique[技术] by (71.8m points)

angular - Subscriber doesn't receive value from .next()

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...