简体   繁体   中英

How to perform async operation from Angular interceptor?

I'm trying to perform an async operation before issuing a network request.

For some reason the network request doesn't even start. I basically want the request to hold until the next function in accessToken$ observable is fired.

As far as I understand I piped the accessToken$ with the observable that is returned from next.handle(req) resulting a middlewear then(..).then(..) behavior.

code:

public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const accessToken$: Observable<string> = from("accessToken");

    return accessToken$.pipe(mergeMap((accessToken: string) => {
        req = req.clone({
            setHeaders: {
                'Authorization' : `${accessToken}`,
            }
        })
        return next.handle(req);
    }));
}

I am trying to figure out why this middlewear behavior isn't working. Or why it is working but the interceptor still hold the request from going out for some reason.

Worth mentioning that if I just return next.handle(req) the request does go through. So my heart tells me that there's something wrong with the observable interaction I defined.

I followed this tutorial: Async HTTP Interceptors with Angular 4.3

If you add a catch error, does it log anything in the output?

  public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const accessToken$: Observable<string> = of("accessToken");

    return accessToken$.pipe(mergeMap((accessToken: string) => {
      const tokenRequest = req.clone({
        setHeaders: {
          'Authorization': `${accessToken}`,
        }
      });
      return next.handle(tokenRequest);
    }),
      catchError((error) => {
        console.log(error);
        return throwError(error);
      }));
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM