从Angular 6的Api中获取并合并数据

时间:2018-10-17 11:51:18

标签: angular typescript api http angular6

如何从API和 对于每个用户ID,他们在一个JSON对象中返回其帖子及其评论?

可以从以下API获取

帖子https://jsonplaceholder.typicode.com/posts

通过以下API的

及其评论https://jsonplaceholder.typicode.com/comments

//Get User Posts And Comments
getUser() {
    this.http.get('https://jsonplaceholder.typicode.com/posts') && this.http.get('https://jsonplaceholder.typicode.com/comments')

    .subscribe(data => {
      this.posts = data;
    });

  }

1 个答案:

答案 0 :(得分:3)

使用forkJoin合并请求

let req1 = this.http.get('https://jsonplaceholder.typicode.com/posts')  
let req2 = this.http.get('https://jsonplaceholder.typicode.com/comments')

forkJoin([req1,req2 ] )
   .subscribe(data => {
      this.posts = data;
});