首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular Bootstrapping:在模块之前加载服务

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

Stack Overflow用户
提问于 2019-02-14 21:24:53
回答 1查看 225关注 0票数 2

我想使用环境感知应用程序设置(我最初的问题和答案在这里:Angular & Docker: Environment aware configuration),它工作得很好。不幸的是,一些模块,如MSAL,需要在导入模块时进行配置。例如:

代码语言:javascript
复制
MsalModule.forRoot({
  clientID: AppSettingsSingletonService.instance.msalConfig.clientId,
  redirectUri: AppSettingsSingletonService.instance.msalConfig.redirectUri,
})

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

代码语言:javascript
复制
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: initApp,
      deps: [
        AppInitService
      ],
      multi: true
    },
  ],

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

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

EN

回答 1

Stack Overflow用户

发布于 2019-10-08 12:30:33

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

代码语言:javascript
复制
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现在看起来像这样:

代码语言:javascript
复制
imports: [
    ...
    MsalModule,
    ...
  ],
  providers: [
    MsalService,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: MSALHttpinterceptor,
      multi: true
    }
  ]

我希望这能回答问题

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54691509

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档