我有一个angular2应用程序(RC6版本),其中一些重要的全局参数是从一个配置文件中加载的,使用一个服务在启动时收集这个文件:
@NgModule({
imports: [ BrowserModule, FormsModule, HttpModule, AppRoutes, SomeCustomModule ],
declarations: [ AppComponent ]
providers: [
ConfigurationService,
{
provide: APP_INITIALIZER,
useFactory: (config: ConfigurationService) => () => {
return config.load().then(configParams=> { return true;});
},
deps: [ConfigurationService, HttpModule],
multi: true
}
],
bootstrap:[ AppComponent ]
})
export class AppModule { }
如这段代码所示,我使用了我称为的ConfigurationService,它通过http调用读取配置文件并返回一些参数(作为承诺)。如果一切顺利,应用程序可以完美加载,这些配置参数可以通过子模块等访问。
问题是,如果这个配置文件没有按预期加载,我如何阻止应用程序加载子模块?(请注意,AppComponent本质上只是一个路由出口,重定向到由多个子模块定义的其他路由)。我可以"禁用"或重定向到一个错误页面,而不是加载由请求路由定义的模块/组件?
要禁用页面的初始路由,并让它根据您的ConfigurationService
进行处理,您必须在AppRoutes
对象中设置 initialNavigation
为false
:
export const AppRoutes = RouterModule.forRoot(ROUTES, {initialNavigation : false});
在你的ConfigurationService
中,你必须注入router
,并根据你的配置使用它来导航。
另一个选择是使用canActivate
路由钩子。在这个钩子中,您可以注入ConfigurationService
并让它决定是否可以加载这个页面。
对于最新版本的angular, initialNavigation
的false
值已被弃用,请使用'disabled'
代替:
{ initialNavigation : 'disabled' }