Dan*_*eve 6 javascript typescript angular-routing angular
我有一个来自静态 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)}`);
});
});
}
}
Run Code Online (Sandbox Code Playgroud)
这个配置被加载到我APP_INITIALIZER的app.module.ts
providers: [
AppConfigService,
{
provide: APP_INITIALIZER,
useFactory: (appConfigService: AppConfigService) => () => {appConfigService.load() },
deps: [AppConfigService], multi: true
}
],
Run Code Online (Sandbox Code Playgroud)
但是我的路由模块,namedAppRoutingModule正在从我的AppConfigService.settings变量中读取一些东西,这太疯狂了,未定义。我的应用程序崩溃了。我希望在APP_INITIALIZERBEFORE 之前触发,AppRoutingModule但情况并非如此:
Uncaught TypeError: Cannot read property 'oldUrl' of undefined
oldUrl是 的属性AppConfigService.settings。我检查了是否AppConfigService.settings设置,它是,在路由模块被触发后正确设置,但这不是我想要的。
我检查了一些其他来源以寻求帮助。我已经使用以下内容作为修复:https : //github.com/angular/angular/issues/14615和https://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 {
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,上述解决方案并没有解决我的问题。我也尝试输入,AppModule但唉,这也无济于事。
非常欢迎任何帮助。
我已经解决了我的应用程序初始化和路由问题,NgRx 监听中央状态以了解系统何时加载,然后激活路由守卫。
但对于直接的解决方案,您需要在加载服务时添加 Route Guard 检查。因此,在您的服务中添加一个loaded: boolean标志,并从 Guard 中检查它,如下所示:
https://github.com/angular/angular/issues/14615#issuecomment-352993695
使用 Observables 可以更好地处理这个问题,我在应用程序中使用 Facades 将所有内容与 NgRx 进行连接,以方便一切: https://gist.github.com/ThomasBurleson/38d067abad03b56f1c9caf28ff0f4ebd
此致。
| 归档时间: |
|
| 查看次数: |
2680 次 |
| 最近记录: |