2016-04-21 59 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();