I have an Angular 5 application with an HTTP interceptor that calls another service whenever it intercepts a request.
I want to make the service configurable using a config file, so I tried using a service that loads the configuration asynchronously during app initialization (using the APP_INITIALIZER hook).
The problem is, that the service I want to use is being instantiated before the configuration service finishes loading the configuration from the config file.
Is there a way to defer the service instantiation until after the configuration service finishes loading the configuration?
You can see the full example in stackblitz.
The most relevant parts are below:
export class InterceptorService implements HttpInterceptor {
constructor(private dependency: InjectedDependencyService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// use InjectedDependencyService to do something on every intercepted request
const userId = this.dependency.getUserId();
console.log("user id:", userId);
return next.handle(request);
}
}
export class InjectedDependencyService {
userId;
constructor(private initializer: InitializerService) {
this.userId = initializer.config.id;
}
// Do something that relies on the configuration being initialized
getUserId() {
console.log("Is configuration initialized?", !!this.initializer.config.id)
return this.userId;
}
}
@Injectable()
export class InitializerService {
config = {};
constructor(private http: HttpClient) { }
initialize() {
// TODO replace with link to a config file
const url = "https://jsonplaceholder.typicode.com/users/1";
return this.http.get(url).toPromise().then(response => {
this.config = response;
console.log("App initialized", this.config);
}, e => console.error(e));
}
}
...
export function initializerServiceFactory(initializerService: InitializerService) {
return () => initializerService.initialize();
}
...
providers: [
InitializerService,
InjectedDependencyService,
{
provide: APP_INITIALIZER,
useFactory: initializerServiceFactory,
deps: [InitializerService],
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: InterceptorService,
multi: true
}
]
...
InitializerService
calls HttpClient which triggers InterceptorService
which in turn calls getUserId()
. You want initialization to finish before any interceptors are used.
You can use HttpBackend
to bypass all interceptors.
@Injectable()
export class InitializerService {
config = {};
constructor(private backend: HttpBackend) { }
initialize() {
const http = new HttpClient(this.backend);
const url = "https://jsonplaceholder.typicode.com/users/1";
return http.get(url).toPromise().then(response => {
this.config = response;
console.log("App initialized", this.config);
}, e => console.error(e));
}
}