[Angular 2] Using Promise to Http

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Angular 2] Using Promise to Http相关的知识,希望对你有一定的参考价值。

You can also use Promise for http:

 

So for the service, you need to call toPromise() method:

  getVehicles(value?: string) {
    return this._http.get(‘api/vehicles.json‘)
      .map((response: Response) => <Vehicle[]>response.json().data)
      .toPromise()
      .catch(this.handleError);
  }

 

Then in your controller, you can get the Promise back:

  getHeroes(value?: string) {
    this.vehicles = this._vehicleService.getVehicles(value);
  }

But notice that, we assign the Promise to the this.vehices. so it means we use ‘async‘ pipe:

<ul>
  <li *ngFor="#vehicle of vehicles | async"
    (click)="select(vehicle)">
    {{ vehicle.name }}
  </li>
</ul>

以上是关于[Angular 2] Using Promise to Http的主要内容,如果未能解决你的问题,请参考以下文章