你如何返回Observable which contains/relies-on an Observable of type Observable ?类型的Observable

问题描述 投票:1回答:1

我在HttpInterceptor函数中编写了一些代码。函数intercept应该返回类型为HttpEvent<any>的Observable。

对我来说棘手的部分是我需要在这个函数中进行异步调用,一旦我进入异步代码的“成功”函数,我只能返回Observable<HttpEvent<any>>

所以我的问题是,如何返回一个真正包含另一个不同类型Observable的正确类型的Observable?

这是我的代码

@Injectable()
export class MyInterceptor implements HttpInterceptor {

    constructor(private valueService: ValueService){}

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const duplicate = req.clone({
            params: req.params.set('newVal', this.valueService.getNewValue())  // this.valueService.getNewValue() returns an Observable<string> !!
        });

        return next.handle(duplicate);
  }
}
angular rxjs observable angular-http-interceptors
1个回答
1
投票
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return this.valueService.getNewValue().
      switchMap((data:string)=>{  //or flatMap
         //You get "data"
         const duplicate = req.clone({
         params: req.params.set('newVal', data);
         return next.handle(duplicate);
       });
}
© www.soinside.com 2019 - 2024. All rights reserved.