无法读取未定义的 属性 'initialNavigation' - Angular v4 AoT

Cannot read property 'initialNavigation' of undefined - Angular v4 AoT

我在尝试将 AoT 改装到现有应用程序中时遇到了一些问题。我收到此错误:

Cannot read property 'initialNavigation' of undefined
RouterInitializer.webpackJsonp.1.RouterInitializer.isLegacyDisabled

我的 AppModule 大概是这样的:

@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      useHash: true,
      enableTracing: true,
      initialNavigation: true,
    }),
  ],
  declarations: [
    AppComponent,
  ],
  exports: [
    AppComponent,
  ],
  providers: [
    Http,
    ConfigService,
    {
      provide: APP_INITIALIZER,
      useFactory: configServiceFactory,
      multi: true,
      deps: [Http, ConfigService],
    },
  ],
  bootstrap: [
    AppComponent,
  ],
})
export class AppModule { }

似乎路由器未定义,并且当此代码路径运行时路由器选项未定义:RouterInitializer.isLegacyDisabled 从路由器模块中的 appInitializer 调用。

此时我不知道该怎么办。我觉得在 APP_INITIALIZER 承诺完成之前就已经解决了路由问题。

这在 JIT 中似乎工作正常,但 AOT 复杂化本身。如果您需要更多详细信息,请告诉我。

编辑:如果我注释掉 APP_INITIALIZER,看起来我可以克服错误。但是我发现路由器也用它来初始化,有没有办法让路由器先等我初始化?

APP_INITIALIZER 导致此问题的原因是路由器现在连接到它。

一个解决方案是完全不使用它来 bootstrap 配置,路由器有一种方法可以通过将其设置 initialNavigation 更改为 false 来手动启动它。

RouterModule.forRoot(routes, {
  initialNavigation: false,
}),

所以我将 APP_INITIALIZER 提供程序移动到 app.component.ts

constructor(
    private router: Router,
    private http: Http,
    private configService: ConfigService,
) {
    // initialise routes once config is loaded
    configServiceFactory(http, configService).subscribe(() => router.initialNavigation());
}

注意:configServiceFactory 基本上是这样的:

return http.get('config.json') // or your remote config service
    .map(m => m.json())
    .do(config => configService.setAppConfig(config)) // store it somewhere
    .catch(err => {
        console.error('Error getting config for app initialisation', err);
        return err;
    });