我正在尝试动态加载MSAL配置文件,但出现错误:
NullInjectorError:没有用于InjectionToken MSAL_CONFIG的提供程序!
代码如下:
import { NgModule, Optional, SkipSelf, APP_INITIALIZER } from "@angular/core";
import { CommonModule } from "@angular/common";
import { HttpClientModule, HTTP_INTERCEPTORS } from "@angular/common/http";
import { MsalModule, MsalInterceptor, MsalConfig, MsalService } from "@azure/msal-angular";
import { ConfigService } from "./config/config.service";
import { MSAL_CONFIG } from "@azure/msal-angular/dist/msal.service";
export function initConfiguration(configService: ConfigService) {
// This will load the json file and store it in a variable
return () => configService.init();
}
export function msalConfigFactory(configService: ConfigService): MsalConfig {
// get the config from the service
return configService.get();
}
@NgModule({
imports: [CommonModule, HttpClientModule, MsalModule],
declarations: [],
providers: [
ConfigService,
{
provide: APP_INITIALIZER,
useFactory: initConfiguration,
deps: [ConfigService],
multi: true
},
{
provide: MSAL_CONFIG,
useFactory: msalConfigFactory,
deps: [ConfigService]
},
MsalService,
{
provide: HTTP_INTERCEPTORS,
useClass: MsalInterceptor,
multi: true
}
]
})
export class CoreModule {
constructor(
@Optional()
@SkipSelf()
parentModule: CoreModule
) {
if (parentModule) {
throw new Error("CoreModule is already loaded. Import only in AppModule");
}
}
}
由于我确实提供了MSAL_CONFIG对象,所以我不明白为什么会引发该错误。
我试图将所有内容都移到app.module
中,但是遇到了同样的错误。我在这里想念什么?
答案 0 :(得分:0)
import { MsalModule } from "@azure/msal-angular";
import { MsalService, MsalConfig } from "@azure/msal-angular";
import { MSAL_CONFIG } from "@azure/msal-angular/dist/msal.service";
import { MsalInterceptor } from "@azure/msal-angular/dist/msal.interceptor";
export function getConfig() {
var request = new XMLHttpRequest();
request.open('GET', "/api/settings", false); // request application settings synchronous
request.send(null);
const response = JSON.parse(request.responseText);
return response as MsalConfig;
}
@NgModule({
imports: [
MsalModule
],
providers: [
MsalService,
{
provide: MSAL_CONFIG,
useValue: getConfig()
},
{
provide: HTTP_INTERCEPTORS,
useClass: MsalInterceptor,
multi: true
},
] ,
bootstrap: [AppComponent]
})
如果找不到解决方案,请尝试一下=)
答案 1 :(得分:0)
尝试提供提供MSAL_CONFIG的自定义类或工厂:
providers: [
...
{
provide: MSAL_CONFIG,
useFactory: MSALConfigFactory
},
...
]
我的MSAL配置提供程序从“ msal”返回“配置”:
import { Configuration } from 'msal';
export function MSALConfigFactory(): Configuration {
return {
auth: {
clientId: 'id',
authority: 'something',
redirectUri: 'uri',
postLogoutRedirectUri: 'uri',
},
cache: {
cacheLocation: 'localStorage'
},
}
};