I am writing some code inside an HttpInterceptor
function. The function, intercept
is supposed to return an Observable with type HttpEvent<any>
.
The tricky part for me is that I need to make an asynchronous call inside this function, and I can only return that Observable<HttpEvent<any>>
once I am inside the "success" function of my asynchronous code.
So my question is, how do I return an Observable of the correct type that really contains another Observable of a different type?
Here is my code
@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);
}
}
答案 0 :(得分: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);
});
}