如何使用RXJS解决深层对象请求

时间:2019-11-14 19:52:35

标签: angular promise rxjs

我需要请求一个端点,并需要从该端点创建/请求下一个端点,但这需要同时完成,就像这样,当我订阅接收结果时,所有下一个“ 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
         }
         ...
     }
  **/
})

如何解决这个问题?我乐于接受Opions和其他解决问题的正确方法

2 个答案:

答案 0 :(得分: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);
  });

答案 1 :(得分:1)

尝试这样:

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