angular - NGRX/RXJS:如何將可觀察流遞迴映射為單一扁平流
我目前在 Ngrx Store 中有以下物件結構:
class Case {
id: string; // an id to uniquely identify the Case
type: string; // an id to identify the type of the Case
links: { [ type: string ]: string }; // a dictionary of links to the current Case.
// the keys are the type of the Case, and the values are the actual id's of the linked Cases.
// These linked cases are in the same store as the Parent Case
}
我可以使用 caseService 中的方法 getCase(caseId: string): Observable<Case> 從商店中取得這個案例
我需要創建一個方法,該方法接受一個案例的 ID,並查詢存儲以獲取該案例及其所有鏈接。這些鏈接需要遞歸地檢索,對所有關聯的案例都是如此。
此方法需要返回案例,以及它的所有連結,結構如下:
class CaseLinks {
case: Case;
links: { type: string, items: CaseLinks[] }[]
}
意思是我需要一個 getCaseLinks(baseCaseId: string): Observable<CaseLinks> 的方法簽名
有沒有任何方法可以從商店查詢一個項目,並且根據案件中的連結,遞歸查詢商店中相關聯的案件,並將所有 Observable 的結果返回成一個單一的、平坦的 observable 流。
以下我已新增了一個 Stackblitz,其中包含一個小範例,展示使用情境以及我想達成的目標。希望這能釐清一些事情:
https://stackblitz.com/edit/angular-ovpgsh
答案#1
假設你已經有 getCase 和 getLink 選擇器,試試這段程式碼:
function getCaseLinks(caseId: string) {
return this.getCase(caseId).pipe(
mergeMap(case => combineLatest(case.links.map(link => getLink(link.id))).pipe(
map(items => ({
case,
links: { type: string, items }
}))
))
)
}
