Home > Software design >  Angular 12 - promise synchronious in interceptor Typescript class
Angular 12 - promise synchronious in interceptor Typescript class

Time:02-21

I use this class in my Angular 12 application:

@Injectable()
export class AppHttpInterceptor implements HttpInterceptor {

constructor(protected authService: AuthService, private router: Router) { }

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log("intercepted request in AppHttpInterceptor#intercept");
    const token = this.authService.getToken().then(response => {
        const token = response;  
        let authReq = req.clone({
            setHeaders: {  
                'Content-Type': 'application/json',
                'x-auth-token': token
            }
        });
        return next.handle(authReq);
    })
  }
} 

My problem with this class is that I should return an Observable<HttpEvent> - I do this in the promise but what I have to do outside or how to solve this anyway?

CodePudding user response:

You can use the rxjs from operator for this.

return from(this.authService.getToken()).pipe(
      switchMap((token) => {
        let authReq = req.clone({
          setHeaders: {  
              'Content-Type': 'application/json',
              'x-auth-token': token
          }
        });
        return next.handle(authReq);
      })
    );
  • Related