簡體   English   中英

如何為 Angular 中的延遲加載模塊加載遠程配置文件

[英]How to load a remote config file for a lazy loaded module in Angular

我有一個 Angular (v6) SPA,其中包含許多延遲加載的模塊。 目前,我有一個 json 文件,其中包含應用程序的配置,可以通過單獨的管理界面進行更改,而無需重建/部署應用程序。 配置文件當前加載在 APP_INITIALIZER 中,它可以很好地確保我在允許應用程序完全引導之前檢索配置。

我想將此配置文件拆分為每個模塊,在 APP_INITIALIZER 中加載一個通用配置,並且僅在該特定模塊延遲加載時才加載其他配置。

是否有公認的或最佳實踐方法來做到這一點? 我似乎在 angular 文檔或一般在網上找不到任何東西。 一種方法可能是在模塊構造函數中獲取配置,但據我所知,我無法阻止模塊繼續加載和設置其所有組件等,直到檢索到此配置文件並將其存儲在某處.

如果我將它設置在延遲加載模塊的根路由上,路由解析器可能會達到這個目的嗎? 例如,我可以不返回任何數據,而是將一些“ConfigService”注入解析器,它會檢索適當的配置文件並存儲它,然后讓解析器解析。

然后這個模塊中的組件可以注入相同的 ConfigService,訪問檢索到的任何配置點。

在模塊初始化期間獲取配置(在構造函數中或在諸如forRoot之類的 static 方法中)將不起作用,因為此時尚未解決依賴關系。 因此,例如,您將沒有HttpClient可用於獲取數據。

什么可能是可行的方法:

1. 提供一個ConfigurationService獲取你的配置文件注入的 URL

@Injectable()
export class ConfigService {

  private config$ = new BehaviorSubject<any | null>(null);
  private loadedConfig = false;

  constructor(@Inject(CONFIG_URL) private configUrl: string,
              private httpClient: HttpClient) {
    this.getConfig();
  }

  getConfig(): Observable<any> {
    if (!this.loadedConfig) {
      this.loadedConfig = true;
      this.httpClient.get(this.configUrl).subscribe(this.config$);
    }
    return this.config$;
  }

}

2. 提供ConfigurationService作為可以動態設置CONFIG_URL的模塊的一部分:

@NgModule({
  providers: [ConfigService],
  imports: [
    HttpClientModule
  ]
})
export class ConfigModule {
  static buildForConfigUrl(configUrl: string): ModuleWithProviders {
    return {
      ngModule: ConfigModule,
      providers: [
        {
          provide: CONFIG_URL,
          useValue: configUrl
        }
      ]
    };
  }
}

3. 在您的功能模塊中導入ConfigModule

現在,當您有一個應該有自己的配置可用的功能模塊時,只需使用buildForConfigUrl ConfigModule

@NgModule({
  exports: [
    MyComponent
  ],
  declarations: [
    MyComponent
  ],
  imports: [
    ConfigModule.buildForConfigUrl('https://my-url/my-config.json')
  ]
})
export class FeatureModule {
}

4. 在您的組件中使用ConfigService

@Component({
  selector: 'my-component',
  template: 'I am your new component. My config is: {{ config$ | async | json }}'
})
export class MyComponent implements OnInit{

  config$: Observable<any>;

  constructor(private configService: ConfigService) {
  }

  ngOnInit(): void {
    this.config$ = this.configService.getConfig();
  }

}

使用這種方法,您可以很好地解耦關注點:您的功能模塊不需要關心配置是如何加載的,但它的組件仍然具有在運行時可用的配置。

如果您想更進一步,您甚至可以從功能模塊中刪除配置 URL 的定義並將其集中移動到您的AppModule

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM