问题描述
在我的应用程序中,我拥有一些在整个应用程序中通用的数据.但是,在加载视图后会填充数据.例如数据,如用户设置,配置文件等. 我知道我们可以在视图加载之前使用resolve来加载数据,但是我无法将resolve添加到所有路由中.因此,当刷新特定的路由时,数据将不可用,或者在加载视图后服务器会做出响应.
In my application, I have some data that is common throughout the application. But the data is populated after the view loads.For example data such as user-settings, profile etc. I know we can use resolve for loading data before the view loads, but I cant add resolve to all the routes.So when a specific route is refreshed the data is not available or the response from the server comes after the view loads.
这怎么办?
下面是我要实现的示例代码.在App.Component.ts中如果令牌存在,则重定向到请求的页面,否则重定向到登录.
Below is the sample code of what I'm trying to achieve.in App.Component.tsif the token exists then redirect to the requested page else redirect to login.
if (token)
{
this.commonServ.loadAppData();
this._router.navigate([(path == 'login' || path == '') ? 'test' : path]);
}
else
this._router.navigate(['login']);
load data方法使用了一些API并将数据加载到模型中.
The load data method hits a few API's and loads data to models.
例如:
public loadAppData() {
this.getUserSettings().then(settings => {
if (settings) {
//Do Something
}
}, error => {
});
this.setUserProfile().then(settings => {
//Do something
});
}
setUserProfile中的数据是在加载视图之后出现的.该怎么办?
The data from setUserProfile comes after the view has loaded.How can this be done?
谢谢!
推荐答案
定义一个先于其他组件加载的外壳"组件,然后向其中添加解析器.
Define a "shell" component that is loaded before any of the other components and add the resolver to it.
应用模板
<router-outlet></router-outlet>
外壳组件模板
<pm-menu></pm-menu>
<div class='container'>
<router-outlet></router-outlet>
</div>
应用程序路由模块
@NgModule({
imports: [
RouterModule.forRoot([
{
path: '',
component: ShellComponent,
resolve: { data: DataResolver }. // <--- HERE
children: [
{ path: 'welcome', component: WelcomeComponent },
{
path: 'products',
canActivate: [AuthGuard],
loadChildren: './products/product.module#ProductModule'
},
{ path: '', redirectTo: 'welcome', pathMatch: 'full' },
]
},
{ path: '**', component: PageNotFoundComponent }
])
],
exports: [RouterModule]
})
export class AppRoutingModule { }
这篇关于在Angular 4中设置数据后的加载路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!