【问题标题】:Fetching and combine data from Api In Angular 6从 Angular 6 中的 Api 获取和组合数据
【发布时间】:2019-03-22 02:17:02
【问题描述】:

如何从 API 中检索数据和 对于每个用户 ID,他的帖子及其 cmets 在一个 JSON 对象中返回?

帖子可以从此 API 获取:https://jsonplaceholder.typicode.com/posts

以及来自此 API 的 cmetshttps://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;
    });

  }

【问题讨论】:

    标签: angular typescript api http angular6


    【解决方案1】:

    使用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;
    });
    

    【讨论】:

    • 这里的data是response1和response2的数组。作为替代方案,您可以.subscribe( ([dataPosts, dataComments]) => { this.posts = dataPosts; this.comments = dataComments;}); 访问回复。
    猜你喜欢
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 2019-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    相关资源
    最近更新 更多