使用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'开头的参数的请求重定向到错误页面。但这似乎很丑陋。如果将来我再添加更多这样的情况,它将不起作用。
尝试创建身份验证防护
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 Guard]将在加载MyAwesomeComponent之前执行检查,您可以稍后根据需要向其添加其他检查。