gpt4 book ai didi

angular - 订阅者没有收到来自 .next() 的值

转载 作者:行者123 更新时间:2023-12-04 00:36:14 26 4
gpt4 key购买 nike

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

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);
}

}

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

. . .

ngOnInit(): void {
this.subscription = this.modalService.isOpen.subscribe(state => {
console.log('`isOpen` in subscription', state);
});
}

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

我的逻辑是,通过使用行为主题,订阅者会收到一个初始值 false,然后我可以在单击具有共享服务实例的其他组件时更改该值。

最佳答案

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

我将 ModalService 移到了最上面的 (app.module.ts) providers 数组的 Providers 中,它按预期工作。

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

关于angular - 订阅者没有收到来自 .next() 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41865348/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com