如何在组件的OnInit()方法中进行两次服务调用?
export class ApartmentComponent implements OnInit {
public apartments: Object[];
public temp: Object[];
constructor(private apartmentService: ApartmentService) {
this.apartmentService = apartmentService;
}
ngOnInit() {
this.apartmentService.getApartments().subscribe(res => this.apartments = res);
this.apartmentService.getStats().subscribe(res => this.temp = res);
console.log(JSON.stringify(this.temp));
}
}
在service.ts
getApartments() {
return this.http.get('./api/businessunits/butype').map((res: Response) => res.json());
}
getStats(){
console.log('Request reached');
return this.http.get('./api/apartments/getstats').map((res: Response) => res.json());
}
在server.ts(ExpressJS)
router.route('/api/businessunits/butype')
.get(function(req, res) {
BusinessUnit.find({unitID: {$exists: true}, UnitType: {$exists: true}},'unitID UnitType',{sort:{unitID: 1}},function(err, businessunits) {
if (err)
res.send(err);
res.json(businessunits);
});
});
router.route('/api/apartments/getstats')
.get(function(req, res) {
//Apartment.aggregate([{$match:{_id: "aptType"}},{$group:{_id:{aptType:"$aptType"},count:{$sum:1}}}],function(err, apartments) {
Apartment.find('aptType',function(err, apartments) {
if (err)
res.send(err);
res.json(apartments);
});
});
当我注释掉getStats()方法调用时,getApartments()可以单独运行。
我收到以下错误
Error: Can't set headers after they are sent.
at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:335:11)
at ServerResponse.header (M:\workspace\Angular2StartKit\node_modules\express
答案 0 :(得分:0)
订阅observable是一种异步操作,这意味着这只是安排稍后完成的任务。
执行console.log(JSON.stringify(this.temp)
时,getStats()
中的服务器调用(如果它实际上是一个 - 我只是假设它)甚至没有发送,因此肯定没有收到响应。
您的问题中的代码也不清楚是否先发送getApartments()
或getStats()
的请求。
要在异步操作中保留特定顺序,您需要正确链接它们,以便在前者完成时执行下一个。
如果您只想打印getStats()
的结果,可以这样做
ngOnInit() {
this.apartmentService.getApartments().subscribe(res => this.apartments = res);
this.apartmentService.getStats().subscribe(res => {
this.temp = res;
JSON.stringify(this.temp)
});
}
替代品
ngOnInit() {
this.apartmentService.getApartments().subscribe(res => this.apartments = res);
this.apartmentService.getStats()
.map(res => this.temp = res);
.subscribe(temp => console.log(JSON.stringify(this.temp));
});
}
或
ngOnInit() {
this.apartmentService.getApartments().subscribe(res => this.apartments = res);
this.apartmentService.getStats()
.map(res => this.temp = res);
.toPromise().then(temp => console.log(JSON.stringify(this.temp));
});
}
如果你想链接2个订阅
this.apartmentService.getApartments().subscribe(res => this.apartments = res);
this.apartmentService.getStats().subscribe(res => this.temp = res);
根据您的要求,有许多可能性,例如flatMap()
。您可能希望它们一个接一个地发送完毕,或者尽快发送它们,然后等待两者完成。有不同的方法来处理错误,......
有关详细信息,请参阅http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html