如何从需要Angular 2中先前API请求的参数的API获取数据?

时间:2017-02-10 07:03:55

标签: api angular rxjs observable

我正在编写一个链接到API的简单Angular 2应用程序。 API具有端点:

  

/工作/:ID

     

/客户端/:ID

我希望我的应用程序显示包含以下数据的表:

  

工作名称

     

职位描述

     

客户名称

     

客户电子邮件

我有一个显示此信息的简单组件

import {Component, OnInit} from '@angular/core'
import {JobService} from './job.service'

@Component({
    selector: 'job',
    template: `
    <table>
    <tr>
    <td>Job Name: {{job.name}}</td>
    <td>Job Description: {{job.description}}</td>
    <td>Client Name: {{client.name}}</td>
    <td>Client Email: {{client.email}}</td>
    </tr>
    </table>`,
    providers: [JobService]
})
export class JobComponent{
    job = {};
    client = {};


    constructor(private _jobService: JobService){}

    ngOnInit(){

        this._jobService.getJob(1)
            .subscribe(job => {
                this.job = job;
            });

        this._jobService.getClient(this.job.client_id)
            .subscribe(client => {
                this.client = client;
            });
    }
}

以及以下服务

import {Http} from '@angular/http'
import {Injectable} from '@angular/core'


@Injectable()
export class JobService {


    constructor(private _http: Http){
    }

    getJob(id){
        return this._http.get(window.__env.apiUrl + 'job/' + id + '/')
        .map(res => res.json());
    }

    getClient(id){
        return this._http.get(window.__env.apiUrl + 'client/' + id + '/')
        .map(res => res.json());
    }


}

这会正确地将作业API调用中的信息写入表中,但会在两个API调用同时运行时返回客户端信息的错误,因此系统尚未从作业API调用接收到client_id 。所以我想知道在第一次完成第二次API调用后,Angular中的正确方法是什么。

为了参考,这里是错误:

  

例外:状态响应:网址为404:http://localhost:8080/au/api/client/undefined/

干杯

2 个答案:

答案 0 :(得分:2)

使用flatMap/mergeMap按顺序运行

ngOnInit(){

    this._jobService.getJob(1)
      .map(res => {
        this.job = job;
        return this.job.client_id;
      })
      .flatMap(client_id => this._jobService.getClient(client_id))
      .subscribe(client => {
          this.client = client;
      });
}

答案 1 :(得分:1)

在第一个电话中插入第二个电话。获得job后,执行第二次api调用

import {Component, OnInit} from '@angular/core'
import {JobService} from './job.service'

@Component({
    selector: 'job',
    template: `
    <table>
    <tr>
    <td>Job Name: {{job.name}}</td>
    <td>Job Description: {{job.description}}</td>
    <td>Client Name: {{client.name}}</td>
    <td>Client Email: {{client.email}}</td>
    </tr>
    </table>`,
    providers: [JobService]
})
export class JobComponent{
    job = {};
    client = {};


    constructor(private _jobService: JobService){}

    ngOnInit(){

        this._jobService.getJob(1)
            .subscribe(job => {
                this.job = job;

                this._jobService.getClient(this.job.client_id)
                    .subscribe(client => {
                       this.client = client;
                    });
            });


    }
}