Angular load external configuration before AppModule loads

后端 未结 3 726
悲哀的现实
悲哀的现实 2020-12-06 06:29

Consider the following scenario (Angular v7):

  1. Load configuration parameters (API server URL and Auth server URL) from an external endpoint (JSON), befo
3条回答
  •  旧巷少年郎
    2020-12-06 07:15

    Angular documentation has a great chapter called NgModule FAQs which contains the following section:

    What if two modules provide the same service?

    ...

    If NgModule A provides a service for token 'X' and imports an NgModule B that also provides a service for token 'X', then NgModule A's service definition "wins".

    In other words, you can override OAuthModuleConfig for your library in AppModule:

    main.ts

    (async () => {
      const response = await fetch('https://api.myjson.com/bins/lf0ns');
      const config = await response.json();
    
      environment['allowedUrls'] = config.apiBaseURL;
    
      platformBrowserDynamic().bootstrapModule(AppModule)
        .catch(err => console.error(err));
    })();
    

    app.module.ts

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    
    import { AppComponent } from './app.component';
    import { OAuthModule, OAuthModuleConfig } from 'angular-oauth2-oidc';
    import { HttpClientModule } from '@angular/common/http';
    import { environment } from '../environments/environment';
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        HttpClientModule,
        OAuthModule.forRoot(),
      ],
      providers: [
        {
          provide: OAuthModuleConfig,
          useFactory: () => ({
            resourceServer: {
              allowedUrls: [environment['allowedUrls']],
              sendAccessToken: true
            }
          })
        }
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule {}
    

    Note that we should also use useFactory instead of useValue so we don't depend on when AppModule is imported.

提交回复
热议问题