user1027620 user1027620 - 3 months ago 78
TypeScript Question

Returning an Observable inside a resolved promise

Trying to return an

Observable
.
How should I go about this?

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


Consumed (not working):

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


Thanks!

Answer

You just need to return this.SetAuthorizationHeader(headers) method, so on resolve of SetAuthorizationHeader method, it will return http.get call observable.

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

Code

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

Consumption

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 + "/users/info"));
}

Get Info Consumption

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