2016-08-21 5 views
3

Observableを返そうとしています。 これについてどうすればいいですか?解決済みの約束の中でオブザーバブルを返す

get(url) : Observable<any> { 
    let headers = new Headers(); 
    this.SetAuthorizationHeader(headers).then(() => { // Resolving a promise 
     return this.http.get(url, { // <-- I need to return the Observable from here 
      headers: headers 
     }); 
    }); 
    } 

消費(動作しない):

public GetInfo() : Observable<any> { 
    return this.authHttpClient.get(this.constants.api_base + "https://stackoverflow.com/users/info") 
     .map((res: Response) => res.json()); 
} 

感謝を!

+0

それは何ですか? –

答えて

4

あなたはthis.SetAuthorizationHeader(headers)メソッドを返す必要があるので、SetAuthorizationHeaderメソッドの解決では、それはhttp.getコールオブザーバブルを返します。

Here you need to remove Observable<any> from get method return type, as actually it is going to return Promise object.

コード

get(url) : any { 
    let headers = new Headers(); 
    //return promise here to continue chain & return inner observable. 
    return this.SetAuthorizationHeader(headers).then(() => { // Resolving a promise 
     return this.http.get(url, { // <-- I need to return the Observable from here 
      headers: headers 
     }); 
    }).map(data => data.json()); 
} 

消費

public GetInfo() : any { //here also it will be any, because you are returning `authHttpClient.get` at the end 
    return this.authHttpClient.get(this.constants.api_base + "https://stackoverflow.com/users/info")); 
} 

情報消費ゲット

this.user.GetInfo().then(obs => 
    obs.subscribe(
     user => { alert(JSON.stringify(user)); }, 
    (error) => { alert(JSON.stringify(error)); } 
); 
+0

こんにちは、お返事ありがとうございます。 'Observable 'メソッドの返り値を取り除くと、コードのどこかで '.map()'を使うことができません。何かアドバイス?ありがとう。 – user1027620

+0

@ user1027620 'Observable 'で動作しますか?私はそうだとは思わない –

+0

残念ながら、この 'get()'メソッドをどのようにして消費することができますか? – user1027620

0

パンカイ・パーカーの作品ですが、返品のタイプはPromise<Observable<any>>です。だからこそ、.then((obs) => obs.subscribe(...))が必要です。

約束を観測可能に変換し、concatMapを組み合わせて2つを組み合わせることで回避できます。

concatMapを使用すると、オブザーバブルの順序を制御できるため、httpヘッダーの前に認可ヘッダーを設定するオブザーバブルが生成されます。

コード

get(url): any { 
    let headers = new Headers(); 
    //transform promise to observable 
    const authHeaderObservable = Observable.from(this.SetAuthorizationHeader(headers)); 

    return authHeaderObservable.concatMap(() => { //return the outer observable 
     return this.http.get(url, { // <-- I need to return the inner Observable from here 
     headers: headers 
     }).map(data => data.json()); 
    }) 
    } 

消費

public GetInfo() : any { //here also it will be any, because you are returning `authHttpClient.get` at the end 
    return this.authHttpClient.get(this.constants.api_base + "https://stackoverflow.com/users/info")); 
} 

ゲット "obseviee" ..がpromiのための1つであるインフォ消費

this.user.GetInfo().subscribe(
     user => { alert(JSON.stringify(user)); }, 
    (error) => { alert(JSON.stringify(error)); } 
); 
関連する問題