【问题标题】:Angular 4 Injecting route in the APP_INITIALIZERAPP_INITIALIZER 中的 Angular 4 注入路径
【发布时间】:2018-03-31 15:29:59
【问题描述】:

我正在尝试在我的 APP_INITIALIZER 中检索 url 中存在的数据

app.module.ts

export function init(config: ConfigService, router: Router) {
    return () => config.load(router);
}


providers : [
    ...
    {
      provide: APP_INITIALIZER,
      useFactory: init,
      deps: [ConfigService, Router],
      multi: true
    },
    ConfigService 
    ... 
]

config-service.ts

@Injectable()
export class ConfigService 
    load(router: Router): Promise<any> {
        console.log('current url : ' + router.url);
        return new Promise(((resolve, reject) => resolve()));
    }
}

不幸的是我得到了

Cannot instantiate cyclic dependency! ApplicationRef ("[ERROR ->]"): in NgModule AppBrowserModule in ./AppBrowserModule@-1:-1

我也尝试在构造函数中使用Injector,但也没有用。

我正在尝试做的事情是否可行?

【问题讨论】:

  • 你能在 stackblitz 上创建一个可重现的问题吗?
  • 干杯伙伴,这应该是公认的答案

标签: angular


【解决方案1】:

config-service.ts 可以改写如下。

@Injectable()
export class ConfigService
    constructor(private injector: Injector){}

    load(): Promise<any> {
        const router = this.injector.get(Router);
        console.log('current url : ' + router.url);
        return new Promise(((resolve, reject) => resolve()));
    }
}

无需在 app.module.ts 中将 Router 作为依赖注入。

【讨论】:

    【解决方案2】:

    我试图做的事情是不可行的,因为 APP_INITIALIZER 发生在路由器初始化之前。 https://medium.com/hackernoon/hook-into-angular-initialization-process-add41a6b7e

    【讨论】:

    猜你喜欢
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-04
    • 2018-10-24
    • 2021-06-25
    • 2017-12-25
    • 2021-09-28
    相关资源
    最近更新 更多