在初始化应用程序之前,Angular 4加载数据

时间:2017-08-09 00:07:49

标签: angular angular-router angular-router-guards

我正在尝试在应用程序启动之前加载一些数据。我需要这样做的原因是因为某些菜单根据某些用户条件限制了访问,例如,基于用户位置。

因此,如果用户还没有位置或者其位置未能访问某些视图,我需要阻止它。

我尝试使用Angular Resolve方法,但没有成功,这就是我所做的:

解决警卫

// 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 },
        ]
    }
];
  

AuthGuard只会检查有效的cookie会话。

如您所见,我尝试阻止访问的路由是company路由。 我可以在第一次加载其他页面时阻止访问,例如,如果第一次访问页面home,然后我导航到页面company,验证工作正常,因为用户数据和位置已经可以使用。

但是,如果第一次访问页面company,它将阻止所有用户在那里导航,因为在LocationGuard尝试验证用户位置时,数据不是可用的。

我还尝试将Resolve替换为CanActivate,但在数据可用后它永远不会启用视图,它会保留在空白页面上。

3 个答案:

答案 0 :(得分:10)

一些事情......

在页面加载之前预取数据是一个很好的解决方案。

阻止访问路线是CanActivate的一个重要用途。

但请注意,旋转变压器仅在检查完所有防护装置后才能工作。因此,您的代码将在运行解析程序之前尝试运行CanActivate

enter image description here

答案 1 :(得分:3)

我认为您可以在应用程序启动之前使用ssh -qnx "useraccount@hostname" "test -f ${file absolute path} || echo ${file absolute path} no such file or directory" 加载数据。

查看此文章。

http://www.gyanstack.com/preload-data-before-app-init-in-angular-5-app_initializer/

答案 2 :(得分:0)

我在this question找到了解决方法。

我找到了使用let address = [10, 176, 12] let key = address[0] * 255 * 255 + address[1] * 255 + address[2] 的方法。我已经尝试使用canActivate来返回.map(),但关键点是最后的Observable,这已经解决了问题。

我会保持开放,因为如果有办法使用.first()获得相同的结果,也许它会更好。