【问题标题】:Mapping multiple http requests nested in one http.get映射嵌套在一个 http.get 中的多个 http 请求
【发布时间】:2018-05-24 02:34:07
【问题描述】:

我的 API 有一个 get 方法,它公开 4 个对象,每个对象包含 1 个 href,我需要在执行第一个 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);
}

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

【问题讨论】:

    标签: angular http


    【解决方案1】:

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

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

    从 'rxjs/observable/forkJoin' 导入 {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);
    }
    

    【讨论】:

    • 谢谢老兄,我已经在做类似的事情了,但是你的实现比我的要干净得多!祝你有美好的一天
    猜你喜欢
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 2013-06-06
    • 1970-01-01
    相关资源
    最近更新 更多