【问题标题】:How to load config.json and use the configuration values in another module?如何加载 config.json 并在另一个模块中使用配置值?
【发布时间】:2019-12-25 08:31:52
【问题描述】:

我正在尝试将所有配置值从 environment.ts 移动到 config.json,因此我可以将相同的构建用于多个不同的环境(开发、登台和生产)。

我一直遵循这里写的建议,VSTS build - replace Angular4 environment variables in Release stage,但就我而言,我在另一个模块中使用了一些配置值,即我正在设置的 core.module up Azure MSAL 详细信息,例如客户端 ID、重定向 Uri 等。

我遇到一个错误,提示我设置 Azure MSAL 所需的配置值尚未加载。

config.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { Config } from 'src/app/model/config';

export let CONFIG: Config;

@Injectable()
export class ConfigService {

  constructor(private http: HttpClient) { }

  public load() {
    return new Promise((resolve, reject) => {
      this.http.get('/assets/config/config.json')
        .subscribe((envResponse: any) => {
          const t = new Config();
          CONFIG  = Object.assign(t, envResponse);
          resolve(true);
        });

    });
  }
}

export function configFactoryService(configService: ConfigService): Function {
  return () => configService.load();
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { LOCALE_ID, NgModule, APP_INITIALIZER } from '@angular/core';

// Load the required calendar data for the de locale
import '@progress/kendo-angular-intl/locales/en-DK/all';

import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { routingModule } from './app.routing';
import { CoreModule } from './core/core.module';
import { SharedModule } from './shared/shared.module';
import { HomeModule } from './modules/home/home.module';
import { ConfigService, configFactoryService } from './core/services/config.service';
import { HttpClient, HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent,
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
    BrowserAnimationsModule,
    HomeModule,
    SharedModule,
    CoreModule,
    routingModule,
    HttpClientModule
  ],
  providers: [
    ConfigService,
    {
      provide: APP_INITIALIZER,
      useFactory: configFactoryService,
      deps: [
        ConfigService,
        HttpClient
      ],
      multi: true
    },
    { provide: LOCALE_ID, useValue: 'en-DK' }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

core.module.ts

import { NgModule } from '@angular/core';
import { NavigationComponent } from './components/navigation/navigation.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { HttpModule } from '@angular/http';
import { AuthMSALCustomInterceptor } from './interceptors/auth.msal.custom.interceptor';
import { MsalModule } from '@azure/msal-angular';
import { CONFIG as environment } from './services/config.service';
import { CommonModule } from '@angular/common';

@NgModule({
  imports: [
    CommonModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule,
    RouterModule,
    HttpModule,
    MsalModule.forRoot({
      clientID: environment.clientID,
      authority: environment.authority,
      validateAuthority: true,
      redirectUri: environment.redirectUri,
      popUp: false,
      consentScopes: [
        `api://${environment.sApplicationId}/access_as_user`,
        `api://${environment.wApplicationId}/access_as_user`,
        `api://${environment.oApplicationId}/access_as_user`,
      ],
      protectedResourceMap: [
        [
          environment.sUrl,
          [`api://${environment.sApplicationId}/access_as_user`]
        ],
        [
          environment.wUrl,
          [`api://${environment.wApplicationId}/access_as_user`]
        ],
        [
          environment.oUrl,
          [`api://${environment.oApplicationId}/access_as_user`]
        ]
      ]
    })
  ],
  exports: [
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule,
    HttpModule,
    NavigationComponent
  ],
  declarations: [NavigationComponent],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthMSALCustomInterceptor,
      multi: true
    }
  ],
})
export class CoreModule { }

我需要能够加载配置值并在 core.module 中使用它们。有没有办法在模块初始化之前加载 config.json 值?

编辑:显示错误发生位置的屏幕截图 - core.module error

【问题讨论】:

  • 使用角度环境文件来设置配置 - medium.com/@balramchavan/…
  • @eduPeeth 我试图不使用角度环境文件(environment.ts、environment.prod.ts 等),因为我不想再次运行构建过程,这就是为什么我正在尝试将配置值移动到配置 json 文件中,这样我就可以进行 JSON 变量替换。
  • Environment.ts 确实是加载该类型配置的错误位置。 stackoverflow.com/questions/43193049/… 的 Matt Tester 提供了完整的答案。他的答案不是官方接受的答案,因此您需要向下滚动。我已经实施了这个解决方案,并且可以确认它有效。
  • 同意@Bytech 我们应该对服务端点 URL 进行运行时配置,而不是编译时配置

标签: angular typescript


【解决方案1】:

经过大量挖掘,包括此链接中的原始博客文章,我在 cmets (https://link.medium.com/QleSbGcCb7) 中找到了一个我最喜欢的实现,它相对简单且易于理解。希望这可以帮助。有关完整实施,请参阅链接,但这是要点。请注意,您需要一个配置文件和一个模型来进行配置。

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

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

【讨论】:

    【解决方案2】:

    这个问题有点老了,但其他人可能会遇到类似的问题。问题是您正在注入 HttpClient,因此 Angular 需要首先解析所有 HTTP_INTERCEPTORS。这也意味着 MsalInerceptor 已加载,因此 MsalService 在 APP_INITIALIZER 之前加载,因此没有加载任何配置。

    你需要做的是摆脱 HttpClient 的注入。而是注入 HttpBackend(确保使用 HttpBackend 而不是 HttpHandler)并在本地创建 HttpClient。请参阅此 GitHub 问题中的完整示例: https://github.com/AzureAD/microsoft-authentication-library-for-js/issues/1403

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-26
      相关资源
      最近更新 更多