angular - 角度路由:字符串中间或前缀之后的参数
问题描述
使用 Angular 9 及其内置路由,我将拥有以下路由定义:
{ path: '/mysubfolder/:param', component: MyAwesomeComponent },
该参数的格式始终为“foo_123”。'foo_' 是一个永远不会改变的硬编码常量。在组件中,我然后按“_”拆分,进一步处理“123”并忘记“foo_”。
这很好用。问题是:应该有一个错误页面来处理所有不存在的页面。它是这样定义的
{ path: '**', pathMatch: 'full', component: ErrorPageComponent }
这也适用于像“/barbarbar”这样的普通 URL。但是,对于“/mysubfolder/blablabla”,它不起作用。当然,我会去MyAwesomeComponent
而不是错误页面(这不是我想要的)。
所以,由于param
总是以'foo_'开头,我想定义类似
{ path: '/mysubfolder/foo_:param', component: MyAwesomeComponent },
在路由中。但这不起作用。这在 Angular 9 中根本不可能,还是我在这里做错了什么?是否有解决该问题的替代方法?(要求是:URL 可能不会改变,所以 '/mysubfolder/foo/:param' 不是一个选项。)
当然,我可以在 MyAwesomeComponent 中将所有带有不以 'foo' 开头的参数的请求重定向到错误页面。但这看起来很丑陋和hacky。如果将来我添加更多这样的案例,它将无法正常工作。
解决方案
尝试创建身份验证保护
import { Injectable } from '@angular/core';
import { Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { CanActivate } from '@angular/router';
@Injectable()
export class RouteGuard implements CanActivate {
constructor(private router: Router) { }
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const encryptedParams = next.params.id
if(<check condition>){
// proceed to the component
return true
}else{
this.router.navigate(['/error']);
return false;
}
}
}
并将其添加到路线
{ path: '/mysubfolder/:param', component: MyAwesomeComponent, canActivate:[RouteGuard] },
auth 守卫将在加载 MyAwesomeComponent 之前执行检查,您可以稍后根据需要向其添加其他检查。
推荐阅读
- jquery - 防止剑道详细信息模板中的重复
- autodesk-forge - 使用动态文件名的 Revit Design 自动化控制打开流程
- java - 声明类型为 T 的新对象
- razor-pages - 如何从 BS“selectpicker”更新缓存的列表/值(使用 c# MVC)
- django-forms - 使用 Django 表单集传递相关字段
- sql - 如何按没有聚合的列分组?
- vue.js - Vue.js 样式绑定不更新样式变量更改的 dom
- angular - How to localize form builder - formio
- javascript - 使用 KENDO 的 Jquery Grid 打印 PDF 时出现奇怪的字符
- php - 在 PUT 请求对象属性显示为字符串之后