【问题标题】:Angular Bootstrapping: Load Service before ModulesAngular Bootstrapping:在模块之前加载服务
【发布时间】:2019-10-08 12:30:32
【问题描述】:

我想使用环境感知应用设置(我的原始问题和答案在这里: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();
  };
}

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

【问题讨论】:

    标签: angular msal


    【解决方案1】:

    您可以做的是在 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
        }
      ]

    希望这个答案

    【讨论】:

      猜你喜欢
      • 2018-06-19
      • 2019-02-27
      • 2022-11-30
      • 2021-07-13
      • 2020-03-01
      • 2021-11-29
      • 2016-10-09
      • 2023-04-05
      • 1970-01-01
      相关资源
      最近更新 更多