[英]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.