Angular 4 在初始化应用程序之前加载数据
Angular 4 load data before initialize the application
我正在尝试在我的应用程序启动之前加载一些数据。我之所以需要这样做,是因为某些菜单根据某些用户条件限制了访问,例如,根据用户位置。
因此,如果用户还没有位置或者其位置未启用以访问特定视图,我需要阻止它。
我尝试使用Angular解决方法,但没有成功,我是这样做的:
解决守卫
// The apiService is my own service to make http calls to the server.
@Injectable()
export class AppResolveGuard implements Resolve<any> {
constructor(
private _api: ApiService,
private _store: Store<IStoreInterface>,
) { }
resolve(): any {
return this._api.apiGet('loadData').subscribe(response => {
this._store.dispatch({
type: USER_FETCH_DATA,
payload: response.usuario
});
return response;
});
}
}
路由
export const routing = [
{
path: '', component: AppComponent, canActivateChild: [AuthGuard], resolve: {app: AppResolveGuard},
children: [
{ path: 'home', component: HomeComponent },
{ path: 'company', canActivate: [LocationGuard], component: CompanyComponent },
]
}
];
The AuthGuard is just going to check for a valid cookie session.
如您所见,我试图阻止访问的路由是 company
路由。
当我第一次加载另一个页面时,我能够阻止访问,例如,如果第一次访问页面 home
然后我导航到页面 company
验证工作正常,因为用户数据和位置已经可用。
但是,如果第一次访问页面 company
,它将阻止所有用户导航到那里,因为在 LocationGuard
尝试验证用户位置时,数据是尚不可用。
我也尝试用 CanActivate
替换 Resolve
,但是在数据可用后它永远不会启用视图,它停留在空白页上。
我在 上找到了解决方法。
我找到了使用 canActivate
的方法。我已经尝试使用.map()
到return和Observable
,但关键是最后的.first()
,这解决了问题。
我会保持打开状态,因为如果有一种方法可以使用 Resolve
实现相同的结果,也许更好。
一些事情...
在页面加载之前预取数据是解析器的一个很好的用途。
阻止访问路由是 CanActivate 的一个很好的用途。
但是请注意,解析器仅在检查所有防护后才起作用。因此,您的代码将尝试 运行 CanActivate before 运行ning 解析器。
我认为您可以使用 APP_INITIALIZER
在应用程序启动之前加载数据。
查看这篇文章:
我正在尝试在我的应用程序启动之前加载一些数据。我之所以需要这样做,是因为某些菜单根据某些用户条件限制了访问,例如,根据用户位置。
因此,如果用户还没有位置或者其位置未启用以访问特定视图,我需要阻止它。
我尝试使用Angular解决方法,但没有成功,我是这样做的:
解决守卫
// The apiService is my own service to make http calls to the server.
@Injectable()
export class AppResolveGuard implements Resolve<any> {
constructor(
private _api: ApiService,
private _store: Store<IStoreInterface>,
) { }
resolve(): any {
return this._api.apiGet('loadData').subscribe(response => {
this._store.dispatch({
type: USER_FETCH_DATA,
payload: response.usuario
});
return response;
});
}
}
路由
export const routing = [
{
path: '', component: AppComponent, canActivateChild: [AuthGuard], resolve: {app: AppResolveGuard},
children: [
{ path: 'home', component: HomeComponent },
{ path: 'company', canActivate: [LocationGuard], component: CompanyComponent },
]
}
];
The AuthGuard is just going to check for a valid cookie session.
如您所见,我试图阻止访问的路由是 company
路由。
当我第一次加载另一个页面时,我能够阻止访问,例如,如果第一次访问页面 home
然后我导航到页面 company
验证工作正常,因为用户数据和位置已经可用。
但是,如果第一次访问页面 company
,它将阻止所有用户导航到那里,因为在 LocationGuard
尝试验证用户位置时,数据是尚不可用。
我也尝试用 CanActivate
替换 Resolve
,但是在数据可用后它永远不会启用视图,它停留在空白页上。
我在
我找到了使用 canActivate
的方法。我已经尝试使用.map()
到return和Observable
,但关键是最后的.first()
,这解决了问题。
我会保持打开状态,因为如果有一种方法可以使用 Resolve
实现相同的结果,也许更好。
一些事情...
在页面加载之前预取数据是解析器的一个很好的用途。
阻止访问路由是 CanActivate 的一个很好的用途。
但是请注意,解析器仅在检查所有防护后才起作用。因此,您的代码将尝试 运行 CanActivate before 运行ning 解析器。
我认为您可以使用 APP_INITIALIZER
在应用程序启动之前加载数据。
查看这篇文章: