Angular5 RXJS递归http请求

问题描述 投票:0回答:1

我目前有这种情况:

#Service My Service
private users = ['user1','user2'];

//Generate list of requests to join
private getHttpList(): any[] {
  let gets = new Array();
  for(let index in this.users)
      gets.push(this.http.get('https://api.github.com/users/' + this.users[index]))
  return gets;
}
...
getList(): Observable<any[]> {
    return forkJoin(this.getHttpList())
}

在我的组件中,我进行订阅

this.MyService.getList().subscribe(results => {
    for(let res in results) {
       //...Do something here
       //..I wanna do the get in of https://api.github.com/users/{user}/starred
    }
})

假设我只知道getList()结果之后的“starred url”,如何才能“同步”这部分,或者这样做的正确形式是什么?

**我尝试硬编码 - 结果是错误的,因为那里“是可迭代的”

this.MyService.getList().subscribe(results => {
        let url = 'https://api.github.com/users/';
        for(let res in results) {//This don't do the things "synchronous"
           this.http.get(url + res.login +'/starred').catch(err => {
               throw new Error(err.message);
           }).subscribe(starred_res => {
               //So we set the starred_list
               res.starred_list = starred_res 
           })
        }
    })

谢谢...

rxjs angular5 fork-join
1个回答
0
投票

据我所知,您希望为每个用户获得已加星标的列表。

最简单的方法是获取所有已加星标的列表并将其与用户结果进行匹配。

// Get users
this.MyService.getList().subscribe((results: any[]) => {

  const url = 'https://api.github.com/users/';

  // Create requests to get starred list for every user
  const starredRequests = results.map(
    res => this.http.get('https://api.github.com/users/' + res.login + '/starred')
  );

  // Wait when all starred requests done and map them with results array
  Observable.forkJoin(starredRequests).subscribe(starred => {

    results.forEach((res, index) => {
      res.starred_list = starred[index];
    });

    console.log(results);
  });

});
© www.soinside.com 2019 - 2024. All rights reserved.