Observable.subscribe()只能工作一次(ngrx\angular2)

Yon*_*n B 12 rxjs angular2-services ngrx angular

我正在订阅组件构造函数中的store属性

constructor(private someService: SomeService){
        someService.someObservable.subscribe((data: Some)=> {
            this.some = data;
            console.log('changed');
        });
}
Run Code Online (Sandbox Code Playgroud)

在服务中,构造函数如下所示:

constructor(private store: Store<any>){
        this.someObservable = <Observable<{}>>store.select('some');
}
Run Code Online (Sandbox Code Playgroud)

我一直在改变这个对象的状态,但是日志只出现一次.还有一点奇怪的是,我正在this.some我的模板中直接访问该属性(没有async管道),它完全更新!看起来该this.some属性正在更新,但next()订阅中的功能不起作用.

帮助任何人?谢谢!

pba*_*aga 5

在我非常相似的情况下,问题是订阅处理程序之一抛出错误。当遇到错误时,可观察流停止发出新值。


icS*_*per 0

您不应该在构造函数中调用服务,这被认为是一种不好的做法。使用 ngOnInit() 方法订阅服务。该方法会在组件加载时自动调用。

尝试这样,这可能会解决你的问题。

import {Component, OnInit} from "@angular/core";

export class YourComponent implements OnInit{

    ngOnInit():void {
       //handle your subscription here
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 你的建议已经到位,但这并不能回答问题。将计算放在构造函数中只会延迟对象的实例化,并且您无法访问属性 (2认同)