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));
}
}

在役.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());
} 

在服务器.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:workspaceAngular2StartKitnode_modulesexpress

订阅可观察性是一种异步操作,这意味着这只是安排稍后要完成的任务。

当执行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

最新更新