2017-03-29 50 views
1

我試圖用rxJS從在angular2可觀察沒有改變打字稿全局變量訂閱方法

這一個HTTP請求處理響應是代碼:

isUserConfirmed(): boolean { 
    let result: boolean = false; 
    this.authService.isUserConfirmed().subscribe(
     retrievedData => { 
     //if no errors from the server 
     if (retrievedData.success) { 
      //if the confirmed flag is true 
      if (retrievedData.payload){ 
      result = true; 
      console.log("i"+result); 
      } else { 
      result = false; 

      } 
     } else { 
      this.showError(retrievedData.message); 
     } 
     }, 
     error => { 
     this.showError(error); 
     }); 
     console.log("o"+result); 
     return result; 
    }, 

showError(error) { 
    //... 
} 

編輯

當我運行這個,我得到這個輸出:

ofalse
itrue

這意味着suscribe方法中的結果值設置爲true,但不會更改返回的結果值。
我如何設法從訂閱區塊內返回設定的值?

回答

1

這是因爲您的控制檯語句在訂閱模塊之外將首先執行。所以你的第一個console.log()將顯示false。緊跟在你的console.log()內的subscribe塊將被執行第二。所以如果成功,結果會是真的。

如果可觀察返回true,結果應該是:

false 
true 

您可以用這種方式

isUserConfirmed(): boolean { 
    let result: boolean = false; 
    return this.authService.isUserConfirmed().subscribe(
     retrievedData => { 
     //if no errors from the server 
     if (retrievedData.success) { 
      //if the confirmed flag is true 
      if (retrievedData.payload){ 
      result = true; 
      console.log("i"+result); 
      } 
     } else { 
      this.showError(retrievedData.message); 
     } 
     return result 
     }, 
     error => { 
     this.showError(error); 
     }); 
    } 
+0

你說得對日誌的順序返回值,所以,我怎麼能設法返回結果來自suscribe塊的值? –

+0

我已經添加了代碼,查看返回語句。 1.返回this.authService.isUserConfirmed()。subscribe()2.返回結果這可能會解決你的問題 –

+0

@PhilippeSimo \t 如果我的答案已經解決了你的問題,你介意接受答案嗎?謝謝。 –