Angular Bootstrapping:在模块之前加载服务

时间:2019-02-14 13:24:53

标签: angular msal

我想使用环境感知的应用程序设置(我的原始问题和解答在这里:Angular & Docker: Environment aware configuration),效果很好。 不幸的是,某些模块(例如MSAL)在导入模块时需要配置。例如:

MsalModule.forRoot({
  clientID: AppSettingsSingletonService.instance.msalConfig.clientId,
  redirectUri: AppSettingsSingletonService.instance.msalConfig.redirectUri,
})

您可能已经看到问题了:我需要加载服务才能获取配置实例,不幸的是,到目前为止,在调用模块之前,我还没有找到一种方法来强制加载。尝试APP_INITIALZER也不起作用:

  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: initApp,
      deps: [
        AppInitService
      ],
      multi: true
    },
  ],

export function initApp(appInitService: AppInitService) {
  return () => {
    return appInitService.initializeAppAsync();
  };
}

由于(对我而言)对这些数据进行硬编码是没有意义的,因此在导入模块之前是否有可能加载服务的方法?

1 个答案:

答案 0 :(得分:0)

您可以做的是在main.ts文件中,从您想要的位置获取配置。 以下面的代码为例:

window.fetch('api/config')
  .then(res => res.json())
  .then((resp) => {
    const msal = resp['msal'];
    const protectedResourceMap: [string, string[]][] = [
      [resp.gatewayAPIBaseUrl, [resp.gatewayApiB2CScope]]
    ];
    const msalConfig = {
      authority: msal.authority,
      authoritypr: msal.authoritypr,
      clientID: msal.clientID,
      validateAuthority: false,
      cacheLocation: 'localStorage',
      postLogoutRedirectUri: resp.applicationURL,
      navigateToLoginRequestUri: false,
      popUp: false,
      unprotectedResources: ['https://angularjs.org/', 'api/config'],
      loadFrameTimeout: 6000,
      protectedResourceMap: protectedResourceMap,
      redirectUri: resp.applicationURL
    };

    window['appSettings'] = resp;

    platformBrowserDynamic([{
        provide: MSAL_CONFIG,
        useValue: msalConfig
      }]).bootstrapModule(AppModule)
      .catch(err => console.log(err));
  })

在这里,我将api / config设置为不受保护的资源,以防止HTTPInterceptor抱怨它未在B2C中注册

所以我先从AppSettings中获取配置,并在MSALService和MSALModule查找之前构建MSAL配置

我的app.module.ts现在看起来像这样:

imports: [
    ...
    MsalModule,
    ...
  ],
  providers: [
    MsalService,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: MSALHttpinterceptor,
      multi: true
    }
  ]

希望这个答案