尝试返回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 + "/users/info")
.map((res: Response) => res.json());
}
谢谢!
答案 0 :(得分:5)
您只需要返回this.SetAuthorizationHeader(headers)
方法,因此在解析SetAuthorizationHeader
方法时,它会返回http.get
来电可观察。
在这里,您需要从get方法返回类型中删除
Observable<any>
, 实际上它将返回Promise
对象。
<强>代码强>
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 + "/users/info"));
}
获取信息消费
this.user.GetInfo().then(obs =>
obs.subscribe(
user => { alert(JSON.stringify(user)); },
(error) => { alert(JSON.stringify(error)); }
);
答案 1 :(得分:2)
Pankaj Parker的作品,但返回类型为Promise<Observable<any>>
。这就是为什么需要额外的.then((obs) => obs.subscribe(...))
。
您可以通过将您的承诺转换为可观察对象来避免这种情况,并使用concatMap
将两者结合起来。
使用concatMap可以控制observable的顺序,因此在http请求之前会发出设置授权头的observable。
<强>代码强>
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 + "/users/info"));
}
获取信息消费
this.user.GetInfo().subscribe(
user => { alert(JSON.stringify(user)); },
(error) => { alert(JSON.stringify(error)); }
);