【问题标题】:CanActivate guards on child routes run before parent Resolve finishCanActivate 子路由上的守卫在父 Resolve 完成之前运行
【发布时间】:2018-08-31 20:36:19
【问题描述】:

我正在尝试在导航到儿童路线之前解析数据,因为我必须在儿童警卫中使用该数据。问题是父解析器,在子守卫被解雇后解析数据。解析器需要很长时间才能解析数据

// 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 应该触发,我该如何实现?

【问题讨论】:

  • 正如您在此处看到的:angular.io/guide/router#resolve-guard,解析器本身被视为守卫,但与路由守卫相比具有次要优先级。所以顺序是不可互换的。首先是路由守卫,然后是解析器。
  • 当我刷新具有子路由的浏览器时,会发生这种情况。有人可以帮忙吗

标签: angular angular-router angular-route-guards angular-resolver


【解决方案1】:

我不确定这是否是正确的方法。但是在经历了很多角度问题之后,我找到了解决方法。

使用 canActivate 代替 resolve 来获取数据并将数据存储在服务中。下面是相同的代码sn-p

@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);
      });
  }
}

它对我很有效。刷新子路由不会有问题。

【讨论】:

  • 似乎是可行的解决方案,但我仍然会要求 Angular 团队解决此问题:github.com/angular/angular/issues/24187
  • 我的解决方案是使用解析器而不是守卫。然后将保持同步顺序和层次结构。
猜你喜欢
  • 1970-01-01
  • 2018-12-04
  • 1970-01-01
  • 1970-01-01
  • 2017-03-28
  • 2017-07-26
  • 2019-02-04
  • 2018-11-14
  • 1970-01-01
相关资源
最近更新 更多