Angular 导入的模块不等待 APP_INITIALIZER

Angular imported modules do not wait for APP_INITIALIZER

我正在尝试在 Angular 11 应用程序中使用 auth0/auth0-angular 库。

我正在关注 loading config dynamically 部分。

它提供了这个示例应用程序模块代码:

// app.module.ts
// ---------------------------
import { AuthModule, AuthClientConfig } from '@auth0/auth0-angular';

// Provide an initializer function that returns a Promise
function configInitializer(
  handler: HttpBackend,
  config: AuthClientConfig
) {
  return () =>
    new HttpClient(handler)
      .get('/config')
      .toPromise()
      .then((loadedConfig: any) => config.set(loadedConfig));   // Set the config that was loaded asynchronously here
}

// Provide APP_INITIALIZER with this function. Note that there is no config passed to AuthModule.forRoot
imports: [
  // other imports..

  HttpClientModule,
  AuthModule.forRoot(),   //<- don't pass any config here
],
providers: [
  {
    provide: APP_INITIALIZER,
    useFactory: configInitializer,    // <- pass your initializer function here
    deps: [HttpBackend, AuthClientConfig],
    multi: true,
  },
],

简而言之,它使用 APP_INITIALIZER 提供程序通过 Promise 动态加载配置,这应该在 Auth0 库的 AuthModule 实例化之前完成,因此它具有从 API 和 AuthClientConfig.set(...) 加载的适当 Auth0 配置值已提前使用这些值调用。

Angular APP_INITIALIZER documentation 说:

If any of these functions returns a Promise, initialization does not complete until the Promise is resolved.

所以,他们的例子从表面上看是有道理的。

但是,当我尝试在自己的应用程序中实际实施此解决方案时,出现以下错误:

Error: Configuration must be specified either through AuthModule.forRoot or through AuthClientConfig.set

这表明 AuthModule 在加载和设置配置之前已经实例化。

在我看来 Angular 在开始实例化导入的模块之前实际上并没有等待 Promise 解析。

我认为这个 StackBlitz demo 在没有任何 Auth0 依赖项的简化示例中演示了问题。

在此示例中,我希望 TestModulePromise 解析后才会实例化,因此我应该看到以下控制台输出:

Inside factory method
Inside promise
Inside timeout
TestModule constructor

但我实际看到的是这样的:

TestModule constructor
Inside factory method
Inside promise
Inside timeout

有人可以帮我理解 APP_INITIALIZER 的确切性质,即什么时候调用它,什么时候 Angular 等待 Promise 解析,什么时候 Angular 开始实例化其他模块,为什么我的 Auth0 设置可能无法正确加载等?

我认为您可能需要将 api 调用包装在 Promise 中。

function configInitializer(handler: HttpBackend, config: AuthClientConfig) {
  return () => fetchAndSetConfig(handler, config);
}

function fetchAndSetConfig() {
  return new Promise((resolve, reject) => {
     new HttpClient(handler).get('/config').toPromise()
       .then((loadedConfig: any) => {
          config.set(loadedConfig);
          resolve(true);
      }); 
  })
}

我在动态 auth0 配置中遇到了同样的问题。我试过了 this solution by Philip Lysenko。主要思想是对主路由使用延迟加载。它对我有用。

还有一个,为您的根路由器配置设置 initialNavigation: 'enabledNonBlocking'

它在“网络”选项卡上的外观:picture

TL;DR - 我最终解决了这个问题,方法是在引导应用程序之前在 main.ts 中加载配置,然后通过自定义注入令牌使配置可用,并且然后我的应用程序配置服务不需要等待它通过 HTTP 加载,因为它已经可用。

详情

我的 AppConfig 界面片段:

export interface AppConfig {
  auth: {
    auth0_audience: string,
    auth0_domain: string,
    auth0_client_id: string,
  };
}

我的常量文件中的自定义 InjectionToken

 const APP_CONFIG: InjectionToken<AppConfig>
  = new InjectionToken<AppConfig>('Application Configuration');

main.ts:

fetch('/config.json')
  .then(response => response.json())
  .then((config: AppConfig) => {
    if (environment.production) {
      enableProdMode();
    }

    platformBrowserDynamic([
      { provide: APP_CONFIG, useValue: config },
    ])
      .bootstrapModule(AppModule)
      .catch(err => console.error(err));
  });

然后在我的主 AppModule 中导入没有配置的 Auth0 AuthModule.forRoot() 并调用我自己的 AppConfigService 来配置 AuthModule.

我仍然需要 APP_INITIALIZER 依赖于 AppConfigService 和 return 一个 Promise 这不知何故让 Angular 等到 AppConfigService constructor 已被调用,但它没有做任何事情(并且仍然不延迟 AuthModule 被初始化),所以我立即解决它。

AppModule:

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    AuthModule.forRoot(),
    ...
  ],
  providers: [
    AppConfigService,
    {
      provide: APP_INITIALIZER,
      useFactory: () => () => {
        return new Promise(resolve => {
          resolve();
        });
      },
      deps: [ AppConfigService ],
      multi: true,
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthHttpInterceptor,
      multi: true,
    },
  ],
  bootstrap: [ AppComponent ],
})
export class AppModule { }

最后,AppConfigService

@Injectable()
export class AppConfigService {

  constructor(
    @Inject(APP_CONFIG) private readonly appConfig: AppConfig,
    private authClientConfig: AuthClientConfig,
  ) {
    this.authClientConfig.set({
      clientId: this.appConfig.auth.auth0_client_id,
      domain: this.appConfig.auth.auth0_domain,
      audience: this.appConfig.auth.auth0_audience,
      httpInterceptor: {
        allowedList: [
          ...
        ],
      },
    });
  }
}

这一切似乎工作正常,虽然我仍然不明白 APP_INITIALIZER 的确切性质并且我不太高兴在构造函数中调用 Auth0 客户端配置的 set 方法而不是文档建议的异步“加载”方法。