簡體   English   中英

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

[英]Observable.subscribe() works only once (ngrx\angular2)

我正在訂閱組件構造函數中的store屬性

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

在服務中,構造函數如下所示:

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

我一直在改變這個對象的狀態,但是日志只出現一次。 還有一點奇怪的是,我正在我的模板中直接訪問this.some屬性(沒有async管道),它完全更新! 看起來像this.some屬性正在更新,但訂閱中的next()不起作用。

幫助任何人? 謝謝!

在我非常相似的情況下,問題是其中一個訂閱處理程序拋出錯誤。 遇到錯誤時,可觀察流停止發出新值。

你不應該在構造函數中調用服務,它被認為是一種不好的做法。 使用ngOnInit()方法訂閱服務。 加載組件時將自動調用此方法。

試試這樣,這可能會解決您的問題。

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

export class YourComponent implements OnInit{

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

}

如果更新屬性並返回相同的對象而不會觸發存儲更新事件,請確保從reducer返回新對象

switch(action.type){

    case MAIN_MENU_TOGGLE : {

Ex返回Object.assign({},appSettings,{isMainMenuExpand:flag})}

我有同樣的問題,我發現原因是你編輯了狀態,沒有為狀態創建新對象,例如:

Do:Object.assign({},state,{smt:changed})}

而不是:Object.assign(state,{smt:changed})}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM