【问题标题】:How to call forkJoin inside a another forkjoin?如何在另一个 forkjoin 中调用 forkJoin?
【发布时间】:2021-07-01 13:48:33
【问题描述】:

我创建了一个这样的路由解析器。我想根据来自 forkjoin 的第一个响应再发出两个 HTTP 请求。我试图在第一个中添加另一个 forkjoin,或者是否有更好的方法来处理这种情况。我正在尝试将两种响应合二为一。

resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
): Observable<any> {
    const userDetails = this._spotify.getCurrentUser();
    const newReleases = this._spotify.getNewReleases();
    const recentPlayedTrack = this._spotify.getUserRecentlyPlayedTracks();
    const resolvedData = forkJoin([
        userDetails,
        newReleases,
        recentPlayedTrack
    ]).pipe(
        map((dashboardApiResults) => {
            const url = `...${dashboardApiResults[1].id}`;
            const options = {
                useUrlPrefix: false
            };
            const req1 = this._http.get(url, options);
            const req2 = this._http.get(url, options);
            const requests = forkJoin([req1, req2]);

            return {
                userDetails: dashboardApiResults[0],
                newReleases: dashboardApiResults[1],
                recentPlayedTracks: dashboardApiResults[2]
            };
        })
    );
    return resolvedData;
}

【问题讨论】:

  • 您应该首先将代码重构为明确命名的实用程序方法。这种方法的原因太多了。
  • 另外,您应该尽可能避免使用any。它使编写正确的代码变得更加困难
  • @Clashsoft,你现在可以检查一下吗,我正在尝试结合两个响应
  • 第二个forkJoin和第一个forkJoin有什么关系?似乎第二个 forkJoin 没有使用第一个的响应。
  • @carlokid,我的实际代码一团糟,所以我简化了它,从第一个响应中我得到了一些 id。使用这些 id,我正在尝试执行第二个 forkjoin。

标签: angular typescript rxjs


【解决方案1】:

根据您回答的问题,我认为您可以使用“of”运算符并将组合结果作为 Observable 类型返回。

map((dashboardApiResults) => {
     const url = `...${dashboardApiResults[1].id}`;
     const options = {
         useUrlPrefix: false
     };
     const req1 = this._http.get(url, options);
     const req2 = this._http.get(url, options);

     return forkJoin([req1, req2]).pipe(
         concatMap([res1, res2]) => {
             return of({
                userDetails: dashboardApiResults[0],
                newReleases: dashboardApiResults[1],
                recentPlayedTracks: dashboardApiResults[2],
                result1: res1,
                result2: res2
             });
         })
     );
})

【讨论】:

  • 我想知道初始地图是否可以是一个 concatMap 以使其更简洁
  • 你真的不需要 concatMap(),你可以使用 map()。那么你就不需要of()了。
  • 另外,这个例子没有返回Observable&lt;Observable&lt;T&gt;&gt;吗?地图返回 forkJoin() 作为其值。
猜你喜欢
  • 2020-09-29
  • 1970-01-01
  • 2019-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-20
  • 1970-01-01
相关资源
最近更新 更多