本文介绍了有角度的.使用APP_INITIALIZER时路由器DI不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在以AppModule
的方式通过APP_INITIALIZER
从服务器预加载应用程序配置:
I'm preloading app configuration from server with APP_INITIALIZER
in following way, AppModule
:
providers: [
ConfigService,
{
provide: APP_INITIALIZER,
useFactory: configServiceFactory,
deps: [ConfigService],
multi: true
}
],
然后,ApiService
从ConfigService
手动注入:
@Injectable()
export class ConfigService {
private api: ApiService;
public constructor(
private injector: Injector
) {
// Avoid cyclid dependencies, inject manually:
this.api = injector.get(ApiService);
}
最后,当将router
注入ApiService
import { Http, Headers, RequestOptionsArgs, Response } from '@angular/http';
import { Router } from '@angular/router';
@Injectable()
export class ApiService {
constructor(
private router: Router,
private http: Http
) {
console.log(router, 'router'); // undefined
debugger;
这是朋克车
有没有人想过如何解决/解决这个问题?
Any thoughts how could it be fixed / worked around ?
推荐答案
此功能适用于anguler 4
This works works in anguler 4
import { APP_INITIALIZER, Provider, Injector } from '@angular/core';
export function appInitializerFactory(
injector: Injector
): () => Promise<any> {
return () => {
return new Promise<any>((resolve, reject) => {
setTimeout(() => {
const router = injector.get(Router);
// do stuff
resolve(this.config);
});
});
}
}
export const appInitializerProvider: Provider = {
provide: APP_INITIALIZER,
useFactory: appInitializerFactory,
deps: [
Injector
],
multi: true
};
这篇关于有角度的.使用APP_INITIALIZER时路由器DI不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!