angular 2 在第一次路由之前调用初始函数 [英] angular 2 call initial function before first routing
问题描述
我有一个应用程序,我想在实际加载应用程序之前从服务器加载所有消息.
I have an app where i want to load all the messages from the server before actually loading the app.
我已将 http 请求放入 OnInit 的应用组件中.
I've put the http request in my app component in OnInit.
但我没有办法让路由在获取第一页之前等待"并且应用程序以空消息开始.
but I don't have a way to make the routing "wait" before fetching the first page and the application is starting with empty messages.
有没有办法做到这一点?
Any way to do this ?
推荐答案
您可以使用APP_INITIALIZER
:
将此添加到您的 AppModule
的 providers 数组中:
Add this to the providers array of your AppModule
:
{provide: APP_INITIALIZER, useFactory: appInitFactory, deps: [MsgLoader], multi: true}
然后创建一个函数工厂来获取您的消息.这应该返回一个返回实际 Promise
的箭头函数:
Then create a function factory which obtains your messages. This should return an arrow function returning the actual Promise
:
export function appInitFactory(msg: MsgLoader): () => Promise<any> {
return () => msg.loadMessages();
}
如果您不介意 AppComponent
加载,但介意加载其子页面,您可以在根路由上使用 initialNavigation
属性:>
If you don't mind that the AppComponent
loads, but do mind about its subpages being loaded, you can use the initialNavigation
property on your root routing:
RouterModule.forRoot(AppRoutes, {initialNavigation: false})
这会阻止加载第一个模块.但是,您应该将一些服务注入到您的 AppComponent
中,该服务处理您的消息的加载,然后路由到所需的模块
This prevents loading of the first module. You should however have some service injected into your AppComponent
which handles the loading of your messages, and then routes to the required module
这篇关于angular 2 在第一次路由之前调用初始函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!