2017-11-04 64 views
0

我有返回可觀察到的包含字符串,像這樣一個功能:angular2越來越字串值,可觀察到局部變量

retrieveDialingCode(countrycode: string): Observable<any> { 
    return this.countries.map(res => res 
      .find(country => country.alpha2 === countrycode) 
      .countryCallingCodes[0] 
     .replace(/\D/g, '')); 
} 

偉大的作品時,我用這樣的:

this.retrieveDialingCode(countrycode).subscribe(res => this.phone.patchValue({ isodialingcode: res })); 

然而,當我使用它像這樣我只得到dialingCode對象:

const dialingCode = this.retrieveDialingCode(phone.isocountrycode).subscribe(res => console.log(res)); 

我到底做錯了什麼?

回答

0

可觀察對象的'問題'在於它們不能輕易轉換爲值,然後用於同步代碼中,因爲您始終需要等待observable發出。

真的,你應該擁有一切取決於retrieveDialingCode結果的訂閱,按您第一次使用的代碼。

您可能會發現圖案

let myVar; 
myObservable.subscribe(value => myVar = value); 
somethingThatUsesMyVar(myVar); 

將工作一些時間,但在解決myObservable任何延遲意味着myVar的不會有預期值。

請注意,如果this.countries不是一個可觀察的數組,但可以讓retrieveDialingCode返回展開值而不是可觀察值,則沒有問題。

+0

是的,我之前做過,但異步是一個問題。代碼取決於retrieveDialingCode的結果是有點廣泛,但如果這是唯一的選擇,那麼我可以把它放在訂閱,有點醜陋恕我直言 – bryanforst

+0

太真實,這是討厭的。你可以通過將下游代碼放入一個方法來實現它,然後'subscribe()'只需要一行內容 - 調用方法,傳遞值。 (對不起,如果這已經很明顯)。 –

0

這是因爲在過去的情況下,您的代碼不返回響應,嘗試使用此:

let dialingCode; 
this.retrieveDialingCode(phone.isocountrycode).subscribe(res => { 
    dialingCode = res; 
}); 

在這裏,我只是subscribedialingCode變量的存儲響應。