【问题标题】:How to solve deep object requests with RXJS如何使用 RXJS 解决深层对象请求
【发布时间】:2020-03-10 21:10:43
【问题描述】:

我需要请求一个端点,并且从这个端点,需要创建/请求一个下一个端点,但这需要同时完成,就像那样,当我订阅接收结果时,所有 nexted "Promises " 需求已经解决了。

import { forkJoin } from 'rxjs';
import { map, mergeMap, switchMap } from 'rxjs/operators';
import { fromFetch } from 'rxjs/fetch';

// https://api.github.com/users?per_page=5 -- **Used just to explain**
fromFetch('https://api.github.com/users?per_page=5').pipe(
  switchMap(res => res.json()),
  mergeMap(item => item),
  map((item: any) => {
    item.my_object_base = {
      // This result need be "completed" join with the current request
      next_item: fromFetch(item.repos_url).pipe(
        switchMap(res => res.json()),
      )
    }
    return item;
  }),
  // which pipe should i run to solve the nexted Observable?
).subscribe((res) => {
  console.log(res)
  /**
     {
         ...
         my_object_base : {
             next_item: Observable // This still is a observable
         }
         ...
     }
  **/
})

如何解决这个问题?我愿意接受意见和另一种解决问题的正确方法

【问题讨论】:

  • 我不知道为什么这被否决了……但如果你能用一个例子来说明你的问题,这会有所帮助。一般来说,使用combineLatest 之类的东西可以确保每个 Observable 在继续之前发出。如果这是您要问的,我可以举个例子。
  • 是的,我认为它对你到底想要做什么感到困惑。仅此代码并不能告诉我们您尝试检索多少页用户,也不能让我们清楚地了解您想要什么数据。提供一个真实的例子,要么尝试工作,要么工作但没有返回正确的结果,你会得到反馈。

标签: angular promise rxjs


【解决方案1】:

更新:我稍微简化了逻辑,应该做我“认为”你想要完成的事情。

https://stackblitz.com/edit/angular-qr86ry

this.http
  .get("https://api.github.com/users?per_page=5")
  .pipe(
    switchMap((response: []) => {
      return from(response);
    }),
    concatMap((response: any) => {
      return this.http.get(response.repos_url).pipe(map((x) => {
        response.my_object_base = x;
        return response;
      }));
    })
  )
  .subscribe(res => {
    console.log(res);
  });

【讨论】:

    【解决方案2】:

    试试这样:

    this.user$ = this.http.get<GithubUser>('https://api.github.com/users/mojombo');
    
    this.hisFirstRepoName$ = this.user$.pipe(
      switchMap(user => this.http.get(user.repos_url).pipe(map(repos => repos[0].name))),
    );
    
    this.data$ = combineLatest([this.user$, this.hisFirstRepoName$]).pipe(
      map(([user,hisFirstRepoName]) => `${user.login}:${hisFirstRepoName}`),
    );
    

    工作演示:

    https://stackblitz.com/edit/angular-ajyxbq

    【讨论】:

    • 好的,这也像我需要的那样工作。谢谢...有2个例子说明了我如何解决这个问题。 @damian-c
    猜你喜欢
    • 2015-12-23
    • 1970-01-01
    • 2020-03-01
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 2018-06-22
    相关资源
    最近更新 更多