Angular load external configuration before AppModule loads

后端 未结 3 737
悲哀的现实
悲哀的现实 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:10

    In addition to @yurzui's answer, if you try this in AOT (e.g. ng build --prod), you will get

    ERROR in Error during template compile of 'AppModule' Function expressions are not supported in decorators in 'AuthModule' 'AuthModule' contains the error at src\app\core\auth.module.ts(29,23) Consider changing the function expression into an exported function.

    so we create an exported function for the factory:

    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';
    
    export function oAuthConfigFactory() : OAuthModuleConfig {
      return {
        resourceServer: {
          allowedUrls: [environment.servers.apiServer],
          sendAccessToken: true
        }
      }
    }
    
    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule,
        HttpClientModule,
        OAuthModule.forRoot(),
      ],
      providers: [
        {
          provide: OAuthModuleConfig,
          useFactory: oAuthConfigFactory
        }
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule {}
    

提交回复
热议问题