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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…