gpt4 book ai didi

javascript - 路由模块在 APP_INITIALIZER 之前加载

转载 作者:太空狗 更新时间:2023-10-29 18:00:28 25 4
gpt4 key购买 nike

我有一个来自静态 AppConfigService 的配置文件的值。 说明如下:

引用代码/文章:https://blogs.msdn.microsoft.com/premier_developer/2018/03/01/angular-how-to-editable-config-files/

import { Injectable } from '@angular/core';
import { AppConfig } from './app-config';
import { HttpClient } from '@angular/common/http';
import { environment } from 'src/environments/environment';

@Injectable()
export class AppConfigService {

static settings: AppConfig;
constructor(private http: HttpClient) { }
load() {
console.log('is this getting fired before routing module check?');
const jsonFile = `assets/config/config.${environment.name}.json`;
return new Promise<void>((resolve, reject) => {
this.http.get(jsonFile)
.toPromise()
.then((response: AppConfig) => {
AppConfigService.settings = <AppConfig>response;
console.log(AppConfigService.settings);
resolve();
})
.catch((response: any) => {
reject(`Could not load file '${jsonFile}':
${JSON.stringify(response)}`);
});
});
}

}

此配置在 app.module.ts 中加载到我的 APP_INITIALIZER

  providers: [
AppConfigService,
{
provide: APP_INITIALIZER,
useFactory: (appConfigService: AppConfigService) => () => {appConfigService.load() },
deps: [AppConfigService], multi: true
}
],

但是我的名为 AppRoutingModule 的路由模块正在从我的 AppConfigService.settings 变量中读取一些东西,这已经够疯狂了,未定义。我的应用程序崩溃了。我希望 APP_INITIALIZERAppRoutingModule 之前触发,但事实并非如此:

未捕获的类型错误:无法读取未定义的属性“oldUrl”

oldUrlAppConfigService.settings 的属性。我检查了 AppConfigService.settings 是否已设置,它是在路由模块被触发后正确设置的,但这不是我想要的。

我检查了一些其他来源以寻求帮助。我已经使用以下内容作为修复:https://github.com/angular/angular/issues/14615https://github.com/angular/angular/issues/14588

@component({})
class App {
constructor(router: Router, loginService: LoginService) {
loginService.initialize();
router.initialNavigation();
}
}

@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(routes, {initialNavigation: false})
],
declarations: [ App ],
bootstrap: [ App ],
providers: [ Guard, LoginService ]
})
export class AppModule {
}

不幸的是,上述解决方案并没有解决我的问题。我也尝试放入 AppModule 但遗憾的是,这也无济于事。

非常欢迎任何帮助。

最佳答案

我已经使用 NgRx 解决了我的应用程序初始化和路由问题,它监听中央状态以了解系统何时加载并在此之后激活路由守卫。

但对于直接解决方案,您需要在加载服务时添加 Route Guard 检查。因此,在您的服务中添加一个 loaded: boolean 标志,并从 Guard 中检查它,如下所示: https://github.com/angular/angular/issues/14615#issuecomment-352993695

不过,使用 Observables 可以更好地处理这个问题,我在我的应用程序中使用 NgRx 连接所有的东西,使用 Facades 来促进一切: https://gist.github.com/ThomasBurleson/38d067abad03b56f1c9caf28ff0f4ebd

最好的问候。

关于javascript - 路由模块在 APP_INITIALIZER 之前加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53649442/

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