[英]Angular2 - Multiple service calls in OnInit method of component
如何在组件的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));
}
}
在服务中
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
订阅可观察对象是一个异步操作,这意味着这只是计划要在以后完成的任务。
当执行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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.