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
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()
}
}