我在HttpInterceptor
函数内编写一些代码。该函数intercept
应该返回类型为Observable的对象HttpEvent<any>
。
对我来说,最棘手的部分是我需要在此函数内进行异步调用,并且只有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);
}
}
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);
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句