2016-04-21 150 views
16

Q)如何将以下可观察项转换为承诺,我可以用.then(...)来调用它?Angular 2:将Observable转换为Promise

我的方法我要转换为一个承诺:

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

service()方法调用:

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

谢谢!

回答

37
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)); 
}); 
+0

得到这个错误: [ts]类型'(assettypes:any)=> void'的参数不能分配给'PromiseConstructor'类型的参数。属性'all'在类型'(assettypes:any)=> void'中缺失。 (参数)assettypes:any – Dave

+0

getAssetTypes()返回什么? –

+0

接口类型的数组AssetType – Dave

7
你不

真的需要这样做只是做...

import 'rxjs/add/operator/first'; 


this.esQueryService.getDocuments$.first().subscribe(() => { 
     event.enableButtonsCallback(); 
     }, 
     (err: any) => console.error(err) 
    ); 
    this.getDocuments(query, false); 

第()确保订阅块只调用一次(在这之后将是,如果你从来没有订阅)一模一样的承诺则()

+0

正确,承诺只有在observables完成时才能解决,使用.first()或.take(1)将确保在第一次发出后就是这种情况。 –

3

观察的可转换答应这样的:

let promise=observable.toPromise();