zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Angular 2] Using Promise to Http

AngularHTTP to Using Promise
2023-09-14 08:59:20 时间

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>