angular 2 在第一次路由之前调用初始函数
angular 2 call initial function before first routing
我有一个应用程序,我想在实际加载该应用程序之前从服务器加载所有消息。
我已将 http 请求放入我的 OnInit 应用程序组件中。
但我无法在获取第一页之前进行路由 "wait",并且应用程序从空消息开始。
有什么办法吗?
您可以为此使用 APP_INITIALIZER
:
将此添加到您的 AppModule
:
的提供程序数组
{provide: APP_INITIALIZER, useFactory: appInitFactory, deps: [MsgLoader], multi: true}
然后创建一个获取消息的函数工厂。这应该 return 一个箭头函数 returning 实际 Promise
:
export function appInitFactory(msg: MsgLoader): () => Promise<any> {
return () => msg.loadMessages();
}
如果您不介意 AppComponent
加载,但介意它的子页面被加载,您可以在根路由上使用 initialNavigation
属性:
RouterModule.forRoot(AppRoutes, {initialNavigation: false})
这会阻止加载第一个模块。但是,您应该在 AppComponent
中注入一些服务来处理消息的加载,然后路由到所需的模块
一个简单的解决方案:
定义路线时,添加 prehome
页面和 PreHomeComponent
:
imports: [
RouterModule.forRoot([
{ path: '', redirectTo: 'prehome', pathMatch: 'full' },
{ path: 'prehome', component: PreHomeComponent },
{ path: 'home', component: HomeComponent },
{ path: 'counter', component: CounterComponent },
{ path: 'fetch-data', component: FetchDataComponent },
{ path: "job/:id", component: JobComponent },
{ path: '**', redirectTo: 'prehome' }
]),
MaterialModule
]
在您的 PreHomeComponent
中从服务器加载您需要的消息,然后重定向到 home
。
我有一个应用程序,我想在实际加载该应用程序之前从服务器加载所有消息。
我已将 http 请求放入我的 OnInit 应用程序组件中。
但我无法在获取第一页之前进行路由 "wait",并且应用程序从空消息开始。
有什么办法吗?
您可以为此使用 APP_INITIALIZER
:
将此添加到您的 AppModule
:
{provide: APP_INITIALIZER, useFactory: appInitFactory, deps: [MsgLoader], multi: true}
然后创建一个获取消息的函数工厂。这应该 return 一个箭头函数 returning 实际 Promise
:
export function appInitFactory(msg: MsgLoader): () => Promise<any> {
return () => msg.loadMessages();
}
如果您不介意 AppComponent
加载,但介意它的子页面被加载,您可以在根路由上使用 initialNavigation
属性:
RouterModule.forRoot(AppRoutes, {initialNavigation: false})
这会阻止加载第一个模块。但是,您应该在 AppComponent
中注入一些服务来处理消息的加载,然后路由到所需的模块
一个简单的解决方案:
定义路线时,添加 prehome
页面和 PreHomeComponent
:
imports: [
RouterModule.forRoot([
{ path: '', redirectTo: 'prehome', pathMatch: 'full' },
{ path: 'prehome', component: PreHomeComponent },
{ path: 'home', component: HomeComponent },
{ path: 'counter', component: CounterComponent },
{ path: 'fetch-data', component: FetchDataComponent },
{ path: "job/:id", component: JobComponent },
{ path: '**', redirectTo: 'prehome' }
]),
MaterialModule
]
在您的 PreHomeComponent
中从服务器加载您需要的消息,然后重定向到 home
。