How use async service into angular httpClient interceptor

前端 未结 7 914
轻奢々
轻奢々 2020-12-09 18:53

Using Angular 4.3.1 and HttpClient, I need to modify the request and response by async service into the HttpInterceptor of httpClient,

Example for modifying the requ

7条回答
  •  离开以前
    2020-12-09 19:33

    I am using an async method in my interceptor like this:

    @Injectable()
    export class AuthInterceptor implements HttpInterceptor {
    
        public constructor(private userService: UserService) {
        }
    
        intercept(req: HttpRequest, next: HttpHandler): Observable> {
            return from(this.handleAccess(req, next));
        }
    
        private async handleAccess(req: HttpRequest, next: HttpHandler):
            Promise> {
            const user: User = await this.userService.getUser();
            const changedReq = req.clone({
                headers: new HttpHeaders({
                    'Content-Type': 'application/json',
                    'X-API-KEY': user.apiKey,
                })
            });
            return next.handle(changedReq).toPromise();
        }
    }
    

提交回复
热议问题