列表中的嵌套请求,Angular 5

时间:2018-04-20 02:44:38

标签: angular

我在工作上有点麻烦,我是使用棱角分明的新人,但在我试着问你们之前我搜索了很多。

让我们假设以下情况,我有一个带有2个端点的API:

第一个返回任何人数据:“api / v1 / people / 1”

{ id: 1, name: 'john', age: '55' }

第二个是一个列表,它返回与人相关的每一个:“api / v1 / people / 1 / related”

{ 
   id: 1,
   father: {
     id: 33,    
   },
   childrens: [
     {id: 34, childrens: [
               { id: 76, childrens: []},
               { id: 532, childrens: []}
              ]
      },
    {id: 354, childrens: [
               { id: 7546, childrens: []},
               { id: 53122, childrens: []}
              ]
 }

我需要让这个分层对象合并第二个服务中每个人的第一个服务的返回。

结果可能是这样的:

{ 
   id: 1, name: 'some name', age: 23  
   father: {
     id: 33, name: 'some name', age: 23  
   },
   childrens: [
     {id: 34, name: 'some name', age: 23   childrens: [
               { id: 76, name: 'some name', age: 23   childrens: []},
               { id: 532, name: 'some name', age: 23   childrens: []}
              ]
      },
     {id: 354, name: 'some name', age: 23   childrens: [
               { id: 7546, name: 'some name', age: 23   childrens: []},
               { id: 53122, name: 'some name', age: 23   childrens: []}
              ]
 }

我知道使用HttpClient和RxJS是可能的,我尝试了很多选项而没有得到任何东西。

你能帮帮我吗?

1 个答案:

答案 0 :(得分:0)

您可以使用RxJS中的Observable.combineLatestnpm install rxjs):

首先,单独调用/api并在成功时设置商店值

api.service.ts

import HttpClient from '@angular/common/http';
import {Observable} from 'rxjs/Observable';

export class ApiService {
   constructor(private http: HttpClient) { }
   getPersonData(personId: string): Observable<any> {
      const headers: {.....}; // set headers as required for the api call
      return this.http.get(`api/v1/people/${personId}`, {headers});
   }

   getDependents(personId: string): Observable<any> {
      const headers: {.....}; // set headers as required for the api call
      return this.http.get(`api/v1/people/${personId}/related`, {headers}); 
   }
}

下一步您需要将这些返回的数据存储在redux存储变量中(您可以搜索如何在js / ts代码中设置它们)

store.ts 说这些是商店变量集:

personData: any;
dependentData: any;
在您的组件类中

最终,当两个数据都可用时,使用Observable.combineLatest组合并映射数据:

import {Component} from '@angular/core';
import {select} from '@angular-redux/store';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/combineLatest';

@Component({....})
export class DataComponent {

   @select() readonly personData: Observable<any>;
   @select() readonly dependentData: Observable<any>;

   getCombinedData() {
      Observable.combineLatest(personData, dependentData)
                .filter((personData, dependentData) => !!personData && !!dependentData) // filter to ensure subscribe does not trigger if any of the two params are undefined
                .subscribe([personData, dependentData]: [any, any]) {
                // now use lodash or javascript map to combine the two data sets returned
       };
   }
}

希望这能为您提供所需的解决方案!