简体   繁体   English

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

[英]Angular2 - Multiple service calls in OnInit method of component

How can I make two service calls in the OnInit() method of the 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));
    }
}

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

in server.ts (ExpressJS) 在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);
     });
}); 

The getApartments() works fine individually when I comment out getStats() method call. 当我注释掉getStats()方法调用时,getApartments()可以单独正常工作。

I am getting the following error 我收到以下错误

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

Subscribing to observables is an async operation, that means this just schedules a tasks to be done later. 订阅可观察对象是一个异步操作,这意味着这只是计划要在以后完成的任务。

When console.log(JSON.stringify(this.temp) is executed, the call to the server in getStats() (if it actually makes one - I just assume it does) wasn't even sent, and therefor definitely no response received yet. 当执行console.log(JSON.stringify(this.temp) ,甚至没有发送对getStats()的服务器的调用(如果它确实使它成为一个-我只是假设确实如此),因此肯定没有收到响应然而。

It is also not clear from the code in your question whether the request for getApartments() or getStats() is sent first. 从您的问题代码中也不清楚是先发送对getApartments()还是getStats()的请求。

To preserve a specific order in async operations, you need to chain them properly so that the next is executed when the former is completed. 要在异步操作中保留特定顺序,您需要正确地链接它们,以便在前一个操作完成时执行下一个操作。

If you just want to print the result of getStats() this can be done like 如果您只想打印getStats()的结果,则可以像

ngOnInit() {
  this.apartmentService.getApartments().subscribe(res => this.apartments = res);

  this.apartmentService.getStats().subscribe(res => {
    this.temp = res;
    JSON.stringify(this.temp)
  });
}

alternatives are 替代品是

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

or 要么

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

If you want to chain 2 subscribes 如果要链2订阅

this.apartmentService.getApartments().subscribe(res => this.apartments = res);
this.apartmentService.getStats().subscribe(res => this.temp = res);

there are lots of possiblilities like flatMap() depending on your requirements. 有很多可能性,例如flatMap()取决于您的要求。 You might want that they are sent one after the other is completed, or send both as soon as possible but then wait for both to complete. 您可能希望它们在另一个完成之后被发送,或者尽快发送两个,然后等待两者都完成。 There are different ways to handle errors, ... 处理错误有多种方法,...

For more details see http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html 有关更多详细信息,请参见http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM