[英]Accessing route param value before APP_INITIALIZER startup service - angular2
[英]Routing Module loads before APP_INITIALIZER
我有一个来自静态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_INITIALIZER
中的app.module.ts
providers: [
AppConfigService,
{
provide: APP_INITIALIZER,
useFactory: (appConfigService: AppConfigService) => () => {appConfigService.load() },
deps: [AppConfigService], multi: true
}
],
但是我的路由模块,名为AppRoutingModule
正在从我的AppConfigService.settings
变量中读取一些内容,这个变量非常疯狂,未完成。 我的应用程序崩溃了。 我希望APP_INITIALIZER
能够在AppRoutingModule
之前AppRoutingModule
但事实并非如此:
Uncaught TypeError: Cannot read property 'oldUrl' of undefined
oldUrl
是AppConfigService.settings
的属性。 我检查了AppConfigService.settings
是否已设置,它是正确的AFTER路由模块被触发但这不是我想要的。
我检查了一些其他来源寻求帮助。 我已经使用以下可能作为修复: 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 {
}
不幸的是,上述解决方案并没有解决我的问题。 我也尝试放入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
最好的祝福。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.