可以在父级解析完成之前运行子级路由上的CanActivate守卫

可以在父级解析完成之前运行子级路由上的CanActivate守卫

本文介绍了可以在父级解析完成之前运行子级路由上的CanActivate守卫的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在导航到子级路由之前解析数据,因为我必须在儿童警卫队中使用该数据.问题是父级解析器,在解雇了儿童看守后解析数据.解析器需要很长时间才能解析数据

I'm trying to resolve data before navigating to children routes as i have to use that data in children guard. The issue is parent resolver, resolves data after the child guard is fired. Resolver takes long time to resolve data

// app.module.ts
const appRoutes: Routes = [
  { path: 'login', component: LoginComponent },
  {
    path: '',
    component: SiteLayoutComponent,
    children: [
      { path: '', redirectTo: 'warehouse', pathMatch: 'full' },
      {
        path: 'warehouse',
        loadChildren: './warehouse/warehouse.module#WarehouseModule'
        // loadChildren: () => WarehouseModule
      }
    ],
    canActivate: [AuthGuard],
    resolve: {
      Site: SiteResolver // should be resolved before the guard is invoked.
    }
  },
  { path: '**', component: PageNotFoundComponent }
];

// warehouse.module.ts
const appRoutes: Routes = [

    { path: '', redirectTo: 'cash', pathMatch: 'full' },
    { path: 'cash', component: CashComponent, canActivate: [RouteGuard] // should be invoked after the parent resolver resloves th data }

];

此处,父解析器(即SiteResolver)在子级守护程序(即RouteGuard)被调用之后解析.我想要的是SiteResolver首先解析数据,然后触发RouteGuard,我如何实现呢?

Here, the parent resolver i.e. SiteResolver resolves after the child guard i.e. RouteGuard is invoked. What i want is SiteResolver to resolve data first and then RouteGuard should fire, how can i achieve that ?

推荐答案

我不确定这是否是正确的方法.但是在经历了许多棘手的问题之后,我找到了解决方法.

I am not sure if this is the correct method. But after going through a lot of angular issues , i found a workaround.

使用canActivate而不是resolve来获取数据并将数据存储在服务中.下面是相同的代码段

Instead of resolve , use canActivate to fetch data and store the data in the service. Below is the code snippet for the same

@Injectable()
export class FetchUserData implements CanActivate {
  constructor(
    private userService: UserService,
    private httpClient: HttpClient
  ) {}
  public modalRef: BsModalRef;
  canActivate() {
    return this.httpClient
      .get("some/api/route")
      .map(e => {
        if (e) {
          this.userService.setUserDetails(e);
          return true;
        }
        return true;
      })
      .catch(() => {
        return Observable.of(false);
      });
  }
}

对我来说效果很好.刷新子路由将没有问题.

It worked for me well. You will have no problem in refreshing the child route.

这篇关于可以在父级解析完成之前运行子级路由上的CanActivate守卫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 16:45