我有一个带有HTTP拦截器的Angular 5应用程序,它在拦截请求时会调用另一个服务。
我想使用配置文件使服务可配置,因此我尝试使用在应用程序初始化期间(使用APP_INITIALIZER钩子异步加载配置的服务)。
问题是,在配置服务从配置文件中加载配置之前,我要使用的服务已被实例化。
是否可以将服务实例化推迟到配置服务完成加载配置之后?
您可以在stackblitz中看到完整的示例。
最相关的部分如下:
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
}
]
...
答案 0 :(得分:2)
InitializerService
调用HttpClient,后者触发InterceptorService
,后者依次调用getUserId()
。您希望在使用任何拦截器之前完成初始化。
您可以使用HttpBackend
来绕过所有拦截器。
@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));
}
}