Angular2 App无法正确初始化浏览器刷新



在开发第一个Angular2应用程序时,我在浏览器中刷新应用时偶然发现问题。

要使用应用程序,用户需要进行身份验证。我有可以处理此操作的AuthenTicationService,并且当用户登录时,获取数据并存储在此authenticationservice中。

应用程序有2个后卫,结算并解决后卫。

解决后卫,如果用户数据在Authenticationservice中存在。如果没有发生或错误,应用程序将导航到登录页面。

i具有dataComponent,使用userId从dataService进行init call方法。从userData的AuthenTicationservice读取UserId。

以下方案崩溃应用程序。用户已记录,一切正常。

刷新浏览器时,在Authenticationservice获取用户数据之前,DataComponent是初始化的。因此,错误的用户ID被发送到DataService和应用程序崩溃。

即使被激活了后卫,也会发生这种情况。DataComponent在Resolve Guard获取用户数据之前先初始化DataComponent。和oninit dataComponent使用错误的用户ID调用数据服务方法。再一次,应用程序崩溃。

问题:

应该使用决心警卫在数据出现之前不加载路线,对吗?然后,为什么在解决后卫响应之前初始化组件?

您有一些建议如何解决此问题?

解决方案:解决方案来自回答的问题。这里的代码看起来。

撤离器守卫:

 resolve(): Observable<UserData> {
    return this.authenticationService.getUserData();

路由:

{ path: 'admin/dashboard', component: DashboardComponent, resolve: {user: ResolverGuard} },

仪表板:

ngOnInit(): void {
    this.activatedRoute.data.subscribe((data:{user:UserData}) => {
        if (data.user) {
            this.dashboardService.getDashboard(data.user.id)
                .subscribe(dashboard => { this.dashboard = dashboard }, err => console.log(err));
        }
    });
}

解析器不是守卫,而是一种加载组件数据的方法,您需要在组件中访问该已解决的数据,例如:

  // routing
  {
    path: 'myroute',
    component: MyComponent,
    resolve: {user: MyResolver}
  }
 // component constructor
 constructor(...
          private activatedRoute: ActivatedRoute) {}
  // ngOnInit
 this.activatedRoute.data
  .subscribe((data: {user}) => {
    // do stuff
  });

最新更新