Use a promise in Angular HttpClient Interceptor

前端 未结 3 947
太阳男子
太阳男子 2020-12-29 05:05

Can I use promise within HttpInterceptor? For example:

export class AuthInterceptor implements HttpInterceptor{
this.someService.someFunction()
         


        
3条回答
  •  佛祖请我去吃肉
    2020-12-29 05:51

    My turn (Thanks to Jota.Toledo and Capripio) :

    1) Switch "fromPromise" to "from" --> fromPromise does not exist on type Observable

    2) Fix 'application/json' quote

    import { Observable, from } from 'rxjs';
    import { switchMap } from 'rxjs/operators';
    
    @Injectable()
    export class AuthInterceptor implements HttpInterceptor {
    
      constructor(private authService: AuthService){}
    
      intercept(req: HttpRequest, next: HttpHandler): Observable> {
    
          return from(this.authService.getToken()).pipe(
            switchMap(token => {
                const headers = req.headers
                    .set('Authorization', 'Bearer ' + token)
                    .append('Content-Type', 'application/json');
                const reqClone = req.clone({
                    headers
                });
                return next.handle(reqClone);
            }));
       }
    }
    

    My version of RxJs: "6.2.2" Hope that helped !

提交回复
热议问题