How use async service into angular httpClient interceptor

前端 未结 7 925
轻奢々
轻奢々 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:27

    If you need to invoke an async function within interceptor then the following approach can be followed using the rxjs from operator.

    import { MyAuth} from './myauth'
    import { from } from 'rxjs'
    
    @Injectable()
    export class AuthInterceptor implements HttpInterceptor {
      constructor(private auth: MyAuth) {}
    
      intercept(req: HttpRequest, next: HttpHandler) {
        // convert promise to observable using 'from' operator
        return from(this.handle(req, next))
      }
    
      async handle(req: HttpRequest, next: HttpHandler) {
        // if your getAuthToken() function declared as "async getAuthToken() {}"
        await this.auth.getAuthToken()
    
        // if your getAuthToken() function declared to return an observable then you can use
        // await this.auth.getAuthToken().toPromise()
    
        const authReq = req.clone({
          setHeaders: {
            Authorization: authToken
          }
        })
    
        // Important: Note the .toPromise()
        return next.handle(authReq).toPromise()
      }
    }
    

提交回复
热议问题