我正在開發的應用程式使用 NgRx 存盤,并且我正在通過 @ngrx/effects 觸發我的 API 呼叫。我認為我的問題可以通過想象一個簡單的待辦事項串列來最好地解釋。以下是我的一種效果的當前狀態的簡化。
persistItem$ = createEffect(() =>
this.actions$.pipe(
ofType(ListActions.ActionType.PersistItem),
mergeMap(({ listItem }) => {
return this.listApiService.modifyListItem(listItem).pipe(
map((updatedItem) => ListApiActions.persistItemSuccess({ updatedItem })),
catchError((error) => of(ListApiActions.persistItemFailure({ failedItem: mergeItemWithError(listItem, error) })))
);
})
)
);
當用戶從串列中選中一個專案并立即再次取消選中它時(因為他們犯了一個錯誤),現在兩個并行請求正在進行中。由于后端希望防止多個用戶覆寫其他更改,因此應用了版本控制。因此,第二個請求將失敗,因為它仍然包含舊版本號。

因此,要使其正常作業,客戶端必須等待請求完成,然后發送第二個請求。
The problem with sending only one request at a time is, that this would also apply if two seperate list items are edited, which should be possible to reduce unnecessary waiting time.
So to summarize my wanted behaviour would be to only wait if there already is a pending request for the same list item. Otherwise, the client should just send the request.
Edit: This is the html template for the list.
<ul>
<li *ngFor="let item of listItems$ | ngrxPush">
{{ item.text }} <button (click)="toggleDone(item)">{{ item.done ? 'Undo' : 'Done' }}</button>
</li>
</ul>
uj5u.com熱心網友回復:
您可以通過組合一些 RxJS 運算子來實作這一點。主要的是groupBy,您將在其中將流分成多個組 - 在您的情況下,這將是一個待辦事項。在每個組中,您可以使用concatMap按順序發送請求。
有關更多資訊和演示,請參閱 Mike Ryan 和 Sam Julien 的以下演講。
https://www.youtube.com/watch?v=hsr4ArAsOL4
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/440214.html
