[英]ngrx effects for a service loop
我是ngrx的新手,正在嘗試為我的ngrx存儲工作使用@Effect函數。 下面的代碼顯示了如果我不使用ngrx存儲,服務將如何工作。 我首先進行http.get調用以獲取列表,然后在該列表上進行迭代以獲取每個列表項。
export interface State {
listItems: ItemDescription[];
itemsData: ItemData[];
}
this.http.get('list-url').subscribe(listItems => {
listItems.map(item => {
this.http.get('list-item-url/' + item.id).subscribe(itemdata => {
state.itemsData.push(itemdata);
});
});
});
我的@Effect函數應該看起來如何? 我是否需要將其分解為兩個@Effect函數,一個用於獲取列表,另一個用於獲取項目?
我會,
我建議您應該檢查示例應用程序並從中學習最佳實踐。
作為參考,@ okan-aslankan,我基於以下代碼解決了此問題:
使用Angular RxJs Observables處理多個http請求並等待所有請求完成
並分成兩個@Effect函數:
@Effect()
listGet$: Observable<Action> = this.actions$
.ofType(items.LIST_UPDATE)
.switchMap(() => this.StoreServ.list(AppSettings.LIST_DIR)
.switchMap(listOfItems => [new ListUpdatedAction(listOfItems), new ReadUpdateAction(listOfItems)]));
@Effect()
readData$: Observable<Action> = this.actions$
.ofType(items.READ_UPDATE)
.mergeMap(listData => this.StoreServ.readData(listData)
.switchMap(items => [new ReadUpdatedAction(items)])
);
哪里:
public list (name: string): Observable<ListResponse> {
return fromPromise(this.itemStore.list(name));
}
public read (logId: string): Observable<PlainLogTable> {
return fromPromise(this.itemStore.read(logId));
}
public readData(list): Observable<PlainLogTable[]> {
return forkJoin(list.payload.map(item => this.read(item.id)));
}
我不知道,我已經聽說過有關RxJS的好消息,但是不禁注意到陡峭的學習曲線和對異步問題的非顯而易見(令人費解的?)解決方案,這與初始的http.get相當明顯。碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.