通过管道使用另一个 API 调用处理 NgRx Effect 中的数据
Processing data in NgRx Effect with another API call through pipe
我正在尝试使用 NgRx 效果处理从第一个 API 调用返回的数据。
fetchPages$ = createEffect(() =>
this._actions$.pipe(
ofType(FETCH_PAGES),
switchMap(() => this._confApi.getPages()
.pipe(
map(pages => {
pages.forEach(page => {
this._confApi.getPageVersion(page.url).pipe(map(version => page.version = version));
});
return pages;
}),
map(pages => SAVE_PAGES({pages}))
)
)
)
);
但在这种情况下,甚至没有调用第一张地图中的 API 调用。我也试过这种方法:
fetchPages$ = createEffect(() =>
this._actions$.pipe(
ofType(FETCH_PAGES),
switchMap(() => this._confApi.getPages()
.pipe(
map(pages => {
pages.forEach(page => {
this._confApi.getPageVersion(page.url).subscribe(version => page.version = version);
});
return pages;
}),
map(pages => SAVE_PAGES({pages}))
)
)
)
);
在调用时,值不会添加到页面 属性(映射到 SAVE_PAGES 实际上并不等待)。
解决这个问题的正确方法是什么?
您缺少 forkJoin
以等待所有 getPageVersion
可观察对象完成。
你可能想要这样的东西
fetchPages$ = createEffect(() =>
this._actions$.pipe(
ofType(FETCH_PAGES),
switchMap(() => this._confApi.getPages()),
switchMap(pages => {
return forkJoin(pages.map(page => this._confApi.getPageVersion(page.url).pipe(
map(version => ({ ...page, version }))
)));
}),
map(pages => SAVE_PAGES({ pages }))
)
);
我正在尝试使用 NgRx 效果处理从第一个 API 调用返回的数据。
fetchPages$ = createEffect(() =>
this._actions$.pipe(
ofType(FETCH_PAGES),
switchMap(() => this._confApi.getPages()
.pipe(
map(pages => {
pages.forEach(page => {
this._confApi.getPageVersion(page.url).pipe(map(version => page.version = version));
});
return pages;
}),
map(pages => SAVE_PAGES({pages}))
)
)
)
);
但在这种情况下,甚至没有调用第一张地图中的 API 调用。我也试过这种方法:
fetchPages$ = createEffect(() =>
this._actions$.pipe(
ofType(FETCH_PAGES),
switchMap(() => this._confApi.getPages()
.pipe(
map(pages => {
pages.forEach(page => {
this._confApi.getPageVersion(page.url).subscribe(version => page.version = version);
});
return pages;
}),
map(pages => SAVE_PAGES({pages}))
)
)
)
);
在调用时,值不会添加到页面 属性(映射到 SAVE_PAGES 实际上并不等待)。
解决这个问题的正确方法是什么?
您缺少 forkJoin
以等待所有 getPageVersion
可观察对象完成。
你可能想要这样的东西
fetchPages$ = createEffect(() =>
this._actions$.pipe(
ofType(FETCH_PAGES),
switchMap(() => this._confApi.getPages()),
switchMap(pages => {
return forkJoin(pages.map(page => this._confApi.getPageVersion(page.url).pipe(
map(version => ({ ...page, version }))
)));
}),
map(pages => SAVE_PAGES({ pages }))
)
);