Use a promise in Angular HttpClient Interceptor
for RxJS 6+ I've updated Jota.Toledo's Answer:
import { fromPromise } from 'rxjs/observable/fromPromise';
@Injectable()
export class AuthInterceptor implements HttpInterceptor{
constructor(private authService: AuthService){}
intercept(req: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
return fromPromise(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);
}));
}
}
UPDATE: using [email protected]
import { from, Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authService: AuthService){}
intercept(request: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
return from(this.authService.getToken())
.pipe(
switchMap(token => {
const headers = request.headers
.set('Authorization', 'Bearer ' + token)
.append('Content-Type', 'application/json');
const requestClone = request.clone({
headers
});
return next.handle(requestClone);
})
);
}
}
ORIGINAL ANSWER
Yes, you could inject the required service into the constructor method of the interceptor, and in the implementation of intercept
retrieve the value, create a new updated http request and handle it.
I'm not good with promises, so you could try the following:
import { fromPromise } from 'rxjs/observable/fromPromise';
@Injectable()
export class AuthInterceptor implements HttpInterceptor{
constructor(private authService: AuthService){}
intercept(req: HttpRequest<any>, next: HttpHandler) : Observable<HttpEvent<any>>{
return fromPromise(this.authService.getToken())
.switchMap(token => {
const headers = req.headers
.set('Authorization', 'Bearer ' + token)
.append('Content-Type', 'application/json');
const reqClone = req.clone({
headers
});
return next.handle(reqClone);
});
}
}