2016-07-27 25 views
3

我正在開發一個Angular 2.0和NGRX的應用程序。我來自React/Redux,所以我仍然在想辦法做些什麼。如何用NGRX改變狀態後執行一些代碼?

當我要打印模板裏面的東西我能寫這樣的事:

@Component({ 
    selector: 'dashboard', 
    directives: [MainContainer], 
    styleUrls: [ 
    './dashboard.style.css' 
    ], 
    template: ` 
    <main-container [section]="viewSection | async"></main-container> 
    ` 
}) 
export class Dashboard { 

    private viewSection: Observable<MainViewSection>; 

    constructor(
    private store: Store<AppState> 
) { 
    this.viewSection = this.store.let(getMainViewSection()); 
    } 

} 

但現在我想一個值發生變化後執行一些代碼(它會使用店內的值作爲輸入(即將改變後視圖)

我知道我可以在陣營componentWillReceiveProps

我發現的唯一的事情,可以是有用的是這樣的:

export class View { 

    constructor(
    private store: Store<AppState> 
) { 
    this.store.select('data').subscribe((val: DataState) => { 
     if (!layer) { 
     return; 
     } 
     layer.setData(val); 
    }); 
    } 

} 

我不認爲這是一種優雅的方式,但我無法找到另一種方式..人們告訴我使用服務(我不知道這是如何適合這種情況),我讀過約@Effects,但我不知道這是我在找什麼。

謝謝!

回答

2

我認爲@Effect是你正在尋找什麼。當某個狀態動作被調用時,@Effect執行。就拿從官方的這個例子NGRX example app

@Effect() clearSearch$ = this.updates$ 
    .whenAction(BookActions.SEARCH) 
    .map<string>(toPayload) 
    .filter(query => query === '') 
    .mapTo(this.bookActions.searchComplete([])); 

使用您指定動作觸發該效果的whenAction方法。在這個例子中,他們使用toPayload,它只返回執行動作的有效載荷。但是你可以訪問整個應用程序的狀態。

這是你如何使用它,例如:

.whenAction(YourActions.SOMETHING) 
    .switchMap(data => this._xhr.send(data.state.yourData) 
+0

我想過這個問題,但我怎麼能觸發對象的方法,一個組件內的? 我有一個地圖圖層,我必須更改一些參數並調用方法。我應該將圖層存儲在狀態中並通過效果改變它嗎? –

+0

是的,我認爲是。如果你想在狀態改變時調用組件中的方法,那麼它不應該是一個組件方法,而應該是一個狀態動作。 –