可观察到的angular无法订阅构造函数或ngOnInit()

时间:2019-05-17 09:53:51

标签: angular typescript

我正在尝试在应用程序中实现一个可观察的概念,在该应用程序中,我的服务被component1调用并发出一个事件,该事件由component 2订阅。

请在下面找到我的代码

服务代码


export class MessageService {
    private subject = new BehaviorSubject<any>("");
    message$ = this.subject.asObservable();
    //observ : Observable <String>;
    sendMessage(message: string) { 
        console.log('sendMesg',message)
        this.subject.next({ text: message });

    }
    clearMessage() {
        this.subject.next("");
   }

Component1代码

  this.data.sendMessage('Printed');

Component2代码

providers: [JsonDataService, MessageService]

constructor(public data?: MessageService)
{}
ngOnInit() {

    this.data.message$.subscribe(res => { console.log('res', res); }, err => { console.log('errrorr', err) });
}

当消息传递到sendMessage函数时,我正在获得控制台,但是我无法获得控制台以及component2中提到的subscription方法的任何响应

2 个答案:

答案 0 :(得分:0)

根据正式文档,该服务的公共实例应由组件共享。 我已经在两个组件中声明了服务,因此无法获取服务发出的数据。

通过将服务声明移至app.module的providers数组中,此问题得以解决。

感谢@Vikas提供帮助和提示。

答案 1 :(得分:0)

确定要同时调用这两个组件。我已经尝试过并且可以正常工作。

https://stackblitz.com/edit/angular-djgzb6