Angular。使用 APP_INITIALIZER 时路由器 DI 不工作
Angular. Router DI not working when using APP_INITIALIZER
我正在使用 APP_INITIALIZER
通过以下方式从服务器预加载应用程序配置,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;
这里是plunker
有什么想法可以修复/解决吗?
此作品适用于角度 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
通过以下方式从服务器预加载应用程序配置,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;
这里是plunker
有什么想法可以修复/解决吗?
此作品适用于角度 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
};