订阅者没有从 .next() 收到值 [英] Subscriber doesn't receive value from .next()

查看:24
本文介绍了订阅者没有从 .next() 收到值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个共享服务来使用 Observable 在组件之间进行通信,使用:http://blog.angular-university.io/how-to-build-angular2-apps-using-rxjs-observable-data-services-pitfalls-to-avoid/ 作为指南:

import { Injectable } from '@angular/core';从 'rxjs/Observable' 导入 { Observable };从 'rxjs/BehaviorSubject' 导入 { BehaviorSubject };@Injectable()导出类 ModalService {private _isOpen: BehaviorSubject= 新行为主题(假);public isOpen: Observable= this._isOpen.asObservable();openModal() {this._isOpen.next(true);}关闭模态(){this._isOpen.next(false);}}

在我的组件中,我订阅了 isOpen,它在订阅时接收一个值:

<预><代码>...ngOnInit(): 无效 {this.subscription = this.modalService.isOpen.subscribe(state => {console.log('订阅中的`isOpen`, state);});}

但是,当我在共享服务实例上触发 .openModal() 时,订阅者永远不会收到新值.我做错了什么?

我的逻辑是,通过使用行为主题,订阅者将收到 false 的初始值,然后我可以更改来自其他具有共享服务实例的组件的点击值.

解决方案

我的应用程序有几个子模块,一个共享模块来注册公共组件,以及它们之间的模块.我已经在共享组件中注册了 ModalService.

我将 ModalService 移动到最上面 (app.module.ts) 提供程序数组的 Providers 中,它按预期工作.

感谢@camaron 的提示.自我注意:永远不要在共享模块中注册提供者:)

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.

解决方案

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

这篇关于订阅者没有从 .next() 收到值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆