2017-06-02 78 views
3

我幾乎可以肯定我應該這樣做,但是我還沒有在Redux文檔中找到任何具體信息。我在我的大多數角分量的模式,是我訂閱/退訂一個終極版店,如:是否有必要從一個Angular組件中取消訂閱Redux商店

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

@Component({ 
    moduleId: module.id, 
    selector: 'selector', 
    templateUrl: 'name.component.html' 
}) 
export class ComponentNameComponent implements OnInit { 
    private unsubscribe : Function; 

    constructor(@Inject(AppStore) private store: Store<AppState>) {} 

    ngOnInit() { 
     this.unsubscribe = this.store.subscribe (()=>{ this.updateFromState(); }); 
    } 
    // Is unsubscribing onDestroy necessary? 
    ngOnDestroy(){ 
     this.unsubscribe(); 
    } 

    this.updateFromState(){ 
     // ... 
    } 
} 

所以,我想知道我是否應該始終從商店退訂,如果我沒會發生什麼「T。

回答

3

是的,你應該在應用程序中不使用時摧毀所有可觀察的內容(unsubscribe)。我不知道Redux store,但我覺得你應該仍然在onDestroy中殺死你的觀察者。

如果您不取消訂閱(),會發生什麼?

當你的組件加載ngOnInit()將認購store,現在如果再次回到一些其他的組件,然後再回到同一個組件第一次,你將有新的subscription與前一次(SO 2個訂閱)一起。這個subscription計數會隨着您重新訪問該組件而增加很多次,這會降低應用程序的性能。所以更安全的一面你應該在創建新的subscription之前殺死之前的版本,通常在ngOnDestroy()之前完成。

+0

Redux訂閱返回一個函數,'Function'是一個Typescript類型。不一樣RxJS Observable/Subsciption [Redux Subscribe](http://redux.js.org/docs/api/Store.html#subscribe) – ktsangop

+0

是我的壞!感謝您通知。 –

+1

你的邏輯似乎是正確的,我認爲Observable模式應該總是以相同的方式使用,但我只是想要一些我無法找到的確鑿證據。我會接受你的答案,除非有人提出了特定的Redux相關參考。謝謝! – ktsangop

相關問題