2017-08-05 116 views
0

我想用AngularFire更新用戶的個人資料圖片。我使用put方法返回promise。在我的promise內部,我使用observable更改用戶信息中的圖像URL。最後,我將圖片的DOM元素的圖片URL更改爲用戶信息中的圖片URL。問題是我的promise在我的observable完成更新之前試圖獲取用戶的圖像URL。有沒有辦法將observable鏈接到promise以便promise只有在observable完成時纔會繼續? 這裏是我的代碼:鏈接可觀察和承諾

authService.ts

updatePicture(profilePicture){ 
    //first put the pictuer in the storage 
    return storageRef.put(profilePicture) 
      .then(snapshot => { 
       downloadURL = snapshot.downloadURL; 
      }) 
       //this is where I use the observable to update user info 
      .then(() => { 
       this.getUserAuth().subscribe(userAuth => { 
        userAuth.updateProfile({ 
         displayName:userAuth.displayName, 
         photoURL:downloadURL 
        }) 
       }) 
      }) 
} 

user.component.ts

// I want this "then" to only happen when my observable is complete. 
authService.updatePicture().then(p => { 
    document.querySelector('img').src = this.userAuth.photoURL); 
} 

回答

0

嘗試包裝可觀察到new promise,並用它在你的鏈承諾如下:

var obs = new Observable(...); 
var promise = new Promise((resolve, reject) => { 
    obs.subscribe(your_on_next, reject, resolve); 
}); 

這應該給你一個承諾,當觀察者終止時將解決。現在,您可以在承諾鏈中按照您的要求使用承諾。只需從該鏈中的另一個then()中返回即可。

您需要添加一些額外的代碼來獲取您需要鏈中下游的可觀察值。