在发送http.Get时从promise获取令牌



我已经尝试了这么长时间来解决这个问题,非常感谢您的帮助。我们有一个方法来解析promise中的token。在解析promise之后,必须在标头中添加令牌,并且必须发送get请求。代码如下

// actually this returns Observable<Observable<T>>
// but this is how it should have return type, only Observable<T>
function get<T>(uri): Observable<T> { 
// create wrapper observable
const ob = new Observable<Observable<T>>(s => {
const promise = getPromiseOperation();
promise.then(y => {
const h = headers.set('Authorization', y);
const client = this.httpClient.get<T>(url, { headers: h });
// now next the actual observable
s.next(client);
s.complete();
});
});
return ob;
}
// consumer
get<Apple>().subscribe(x => x.subscribe(y => y));
// How I Actually want to consume is
get<Apple>().subscribe(x => x)
// I also would like to support pipe rxjs operators on the result
get<Apple>().pipe(map(x => x)).subscribe(x => x)

非常感谢您的帮助。它是否与Rxjs中的mergeMaps有关?

您可以像下面的一样简单地压平链

const getApple$ = defer(() => getPromiseOperation()).pipe(
switchMap(y => {
const h = headers.set('Authorization', y);
return this.httpClient.get<T>(url, { headers: h })
})
)
getApple$.subscribe(x => console.log(x))

参考文献

RxJS defer
RxJS switchMap

最新更新