映射嵌套在一个http.get中的多个http请求

时间:2018-05-23 17:28:27

标签: angular http

我的API有一个get方法,它暴露了每个包含1个href的4个对象,我需要在执行第一个GET之后用href进行4个get请求

API合约

{
  "tipoDocumentoCliente": "CPF",
  "documentoCliente": "9687023767",
  "nomeCliente": "RAFAEL HERMOGENES DE MENDONCA",
  "dataNascimentoCliente": "1982-04-14T00:00:00",
  "sexoCliente": "MASCULINO",
  "estadoCivilCliente": "CASADO",
  "cpfCliente": "9687023767",
  "cnpjCliente": null,
  "celCliente": null,
  "profissaoCliente": "Analista de desenvolvimento de sistemas",
  "rendaCliente": 12000,
  "escolaridadeCliente": null,
  "matricula": 0,
  "contas": {
    "method": "Get",
    "rel": "get-contas",
    "href": "http://localhost:62474/api/v1/Contas/9687023767"
  },
  "enderecos": {
    "method": "Get",
    "rel": "get-enderecos",
    "href": "http://localhost:62474/api/v1/Endereco/9687023767"
  },
  "telefones": {
    "method": "Get",
    "rel": "get-telefones",
    "href": "http://localhost:62474/api/v1/Phones/9687023767"
  },
  "emails": {
    "method": "Get",
    "rel": "get-emails",
    "href": "http://localhost:62474/api/v1/Emails/9687023767"
  }
}

这是我如何向我的api提出单一请求

public ObterFundos<T>(cpf: number): Observable<T> {
    return this.http.get<T>(this._calcularFundosUrl + cpf);
}

我不知道如何使用请求中的hrefs

1 个答案:

答案 0 :(得分:1)

您需要先在组件中订阅您的方法,然后使用forkJoin来获取和组合来自不同网址的数据

<强> component.ts

desiredData: any;

this.service.ObterFundos(<number>).subscribe(res => {
    forkJoin(this.service.getDataFromUrl(res.contas.href), 
                this.service.getDataFromUrl(res.enderecos.href), 
                this.service.getDataFromUrl(res.telefones.href), 
                this.service.getDataFromUrl(res.emails.href)).subscribe(result => {
        res.contas['data'] = result[0];
        res.enderecos['data'] = result[1];
        res.telefones['data'] = result[2];
        res.emails['data'] = result[3];
        this.desiredData = res;
        console.log(this.desiredData);
    });
});
  

从&#39; rxjs / observable / forkJoin&#39;中导入{forkJoin};

<强> service.ts

public ObterFundos<T>(cpf: number): Observable<T> {
    return this.http.get<T>(this._calcularFundosUrl + cpf);
}

getDataFromUrl(url) {
    return this.http.get(url);
}