繁体   English   中英

Angular canActivate router guard不工作

[英]Angular canActivate router guard not working

出于某种原因,我的成本类别详细信息守卫没有按预期工作。 当我提供有效的“id”编号或单击成本类别组件中的项目时,到成本类别详细信息的路由工作得很好。 如果我输入“localhost/44300/cost-ca/42”,那么我应该被重定向回我的 cost-categories.component.html 页面,因为我的数据中不存在该“id”。 但是,当我键入不存在的 id 时,守卫似乎不起作用,并将我重定向到没有任何数据的成本类别详细信息页面。

如果数据中的“id”是 null,那么我想显示一个警报并返回到 cost-categories-list 页面。 请帮忙!

成本类别-details.guard.ts

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class CostCategoriesDetailsGuard implements CanActivate {
  constructor(private router: Router) { }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    let id = +next.url[1].path;
    if (isNaN(id) || id < 1) {
      alert('Invalid well Id');
      this.router.navigate(['/cost-categories']);
      return false;
    }
    return true;
  }
}

应用程序路由模块.ts

const routes: Routes = [

  {path: '', component: CostCompareComponent, canActivate: [MsalGuard]},
  {path: 'cost-categories', component: CostCategoriesComponent},
  {path: 'cost-categories/:id', component: CostCategoriesDetailsComponent, canActivate: [CostCategoriesDetailsGuard]},
  {path: '**', component: NotfoundComponent},
];

这段代码:

if (isNaN(id) || id < 1) {
  alert('Invalid well Id');
  this.router.navigate(['/cost-categories']);
  return false;
}

仅检查 id 是否为数字以及该数字是否大于 1。此守卫中没有代码来检查是否存在具有该数字的现有 Id。

根据代码的其他部分,您最好从详细信息页面本身重定向“未找到”。 因此,当详细信息页面中的代码请求具有未找到 id 的产品时,它将使用this.router.navigate导航回来。

或者考虑使用路由解析器来获取数据。 然后,您可以从路由解析器重新路由,而无需先转到详细信息页面。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM