Angular2 – 在组件的OnInit方法中调用多个服务

如何在组件的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 

       

网上收集的解决方案 "Angular2 – 在组件的OnInit方法中调用多个服务"

订阅observables是一个asynchronous操作,这意味着这只是安排稍后完成的任务。

当执行console.log(JSON.stringify(this.temp) ,在getStats()调用服务器(如果它实际上是一个 – 我只是假设它)甚至没有被发送,因此,没有收到响应然而。

从你的问题中的代码也不清楚getApartments()getStats()的请求是先发送的。

要在asynchronous操作中保留特定的顺序,您需要正确链接它们,以便在前一个完成时执行下一个顺序。

如果你只是想打印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()取决于您的要求的flatMap() 。 你可能想要一个接一个地完成发送,或者尽快发送,但是等待两个完成。 有不同的方式来处理错误,…

欲了解更多详情,请参阅http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html