[英]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.