gpt4 book ai didi

angular - 在 APP_INITIALIZE 之后初始化模块

转载 作者:行者123 更新时间:2023-12-05 08:08:10 26 4
gpt4 key购买 nike

在我的 Angular 6 应用程序中,我通过这样的 Http 服务加载我的外部化配置:

export function getSettings(appLoadService: ConfigLoadService) {
return () => appLoadService.getSettings();
}

@NgModule({
imports: [
CommonModule
],
declarations: [],
providers: [
ConfigLoadService,
{provide: APP_INITIALIZER, useFactory: getSettings, deps: [ConfigLoadService], multi: true}]
})
export class AppLoadModule {
}

服务:

@Injectable()
export class ConfigLoadService {

constructor(private http: HttpClient) {
}

getSettings(): Subscription {
console.log("Loading config from server...");
return this.http
.get("/config.json")
.subscribe((config: any) => {

AppSettings.API_BASE_URL = config.API_BASE_URL;

console.log("API_BASE_URL: " + AppSettings.API_BASE_URL);
});
}
}

现在我想添加一个外部依赖,需要使用当前配置进行初始化:

@NgModule({
imports:
DepModule.forRoot({
apiBaseUrl: AppSettings.API_BASE_URL
}),
],[...]

这里的问题是依赖项是在 APP_INITIALIZER 之前导入和初始化的,因此没有正确配置。我在这里缺少什么?

最佳答案

APP_INITIALIZER 提供者工厂方法必须返回一个 promise

所以你会做这样的事情:

@Injectable()
export class ConfigLoadService {

private myConfig;
constructor(private http: HttpClient) {
}
getSettings() {
return this.http.get('/config.json')
.toPromise()
.then(data => {
this.myConfig = data;
});
}

getConfig() {
return this.myConfig;
}
}

Juri 写了一篇关于它的博客你可以阅读更多 App Runtime Config

关于angular - 在 APP_INITIALIZE 之后初始化模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51878432/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com