【发布时间】:2017-06-28 10:43:40
【问题描述】:
我正在编写一个链接到 API 的简单 Angular 2 应用程序。 API 有端点:
/job/:id
/client/: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 .所以我想知道 Angular 在第一个 API 调用完成后进行第二个 API 调用的正确方法是什么。
为了参考,这里是错误:
例外:响应状态:404 未找到 URL:http://localhost:8080/au/api/client/undefined/
干杯
【问题讨论】:
标签: api angular rxjs observable