typescript – Angular 2:将Observable转换为Promise

前端之家收集整理的这篇文章主要介绍了typescript – Angular 2:将Observable转换为Promise前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
问:如何将以下observable转换为promise,以便我可以用.then(…)调用它?

我希望转换为承诺的方法

this._APIService.getAssetTypes().subscribe(
    assettypes => {
        this._LocalStorageService.setAssetTypes(assettypes);
    },err => {
        this._LogService.error(JSON.stringify(err))
    },() => {}
  );

调用的服务方法

getAssetTypes() {
    var method = "assettype";
    var url = this.apiBaseUrl + method;

    return this._http.get(url,{})
      .map(res => <AssetType[]>res.json())
      .map((assettypes) => {
        assettypes.forEach((assettypes) => {
          // do anything here you might need....
      });
      return assettypes;
    });      
  }

谢谢!

import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';

...

this._APIService.getAssetTypes()
.map(assettypes => {
  this._LocalStorageService.setAssetTypes(assettypes);
})
.toPromise()
.catch(err => {
  this._LogService.error(JSON.stringify(err));
});

猜你在找的Angularjs相关文章