【问题标题】:Prevent componenet from loading before guard completes防止组件在防护完成之前加载
【发布时间】:2018-03-12 09:23:19
【问题描述】:

我想知道是否有办法在保护完成之前阻止组件加载?

问题

我的组件在警卫检索有关用户的相关信息之前加载,因此加载检查失败。

我目前的设置如下:

应用路由模块

{
    path: 'sub', component: MasterComponent, canActivateChild: [AuthGuard],
    children: [
      { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
      { path: 'dashboard', component: DashboardComponent }    
    ]
  },

AuthGuard - canActivateChild 方法

canActivateChild(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {

    return this.secService.isAuthorized()
      .map((profilePresent: boolean) => {
        if (!profilePresent) {
          this.secService.getProfile().subscribe(
            (data: any) => {
              sessionStorage.setItem('profile', JSON.stringify(data));

              return false;
            }
          );

          return true;
        }

        this.secService.redirectToAuthorization();
        return false;
      });
  }

在我的 Dashboard.component.ts 中:

ngOnInit() {
var name = JSON.parse(sessionStorage.getItem('profile')).name;

console.info(name);
}

这一切都会在控制台上引发错误:

ERROR TypeError: Cannot read property 'name' of null

跟踪它我注意到在组件加载之前防护没有完成,因此出现错误(它当时不存在)。

关于如何管理的任何想法

【问题讨论】:

  • 还有canLoadCanActivateResolve。也许其中之一会帮助你。

标签: angular rxjs


【解决方案1】:

因此,如果我理解正确,您需要在从 this.secService.getProfile() 检索数据后完成从 canActivateChild 返回的 Observable。

你只需要重组你的 Observable 链而不是进行嵌套订阅:

return this.secService.isAuthorized()
  .concatMap((profilePresent: boolean) => {
    if (!profilePresent) {
      return this.secService.getProfile()
        .do(data => sessionStorage.setItem('profile', JSON.stringify(data))
        .mapTo(true); // I'm not sure what you really need to do here
    }

    this.secService.redirectToAuthorization()
    return Observable.of(false);
  });

请注意,您无法从 subscribe 调用返回值,所以我不知道您到底想做什么,但我希望您明白这一点。

【讨论】:

  • 在接收回数据之前仍会加载组件。完全没有意义。
  • 你能做一个演示吗?无论如何,您所说的“负载”是什么意思?它显示组件或加载包或什么?
  • 不容易。因为它在 getProfile() 返回值之前触发 ngOnInit()。据我了解,在 canActivateChild 返回值 true 之前,甚至不应该加载路径。然而我们在这里,它并没有返回真实,但它仍然在加载孩子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-13
  • 1970-01-01
  • 2017-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多