2016-04-21 29 views
16

S) Aşağıdakileri gözlemlenebilir hale nasıl dönüştürürüm, böylece .then(...) ile arayabilirim?Açısal 2: Değiştirilebilir Dönüştürme Sözlüğü

Benim yöntemim bir söz dönüştürmek istediğiniz:

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

hizmet yöntemi çağırır:

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

teşekkürler! Eğer yok

cevap

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

bu hatayı alın: [ts] '(assettypes: any) => void' türünde argüman 'PromiseConstructor' türünde bir parametreye atanamaz. 'Tümü' özelliği '(assettypes: any) => void' türünde yok. (parametre) assettypes: Herhangi bir – Dave

+0

'getAssetTypes()' ne döndürür? –

+0

Bir dizi arayüz tipi AssetType – Dave

7

gerçekten ... sadece bunu yapmanız gerekir

import 'rxjs/add/operator/first'; 


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

ilk() yalnızca (bundan sonra abone olmamış gibi olacaktır) bir kez denir bloğu abone sağlar, bir vaatler tam olarak aynı sonra()

+0

Doğru, söz ancak yalnızca gözlemlenebilirler tamamlandığında çözülür, .first() veya .take (1) kullanılarak ilk yayından sonra durumun doğru olduğundan emin olun. –

3
gözlemlenebilir böyle söz dönüştürülebilir

:

let promise=observable.toPromise();