首页 > 解决方案 > 角度路由:字符串中间或前缀之后的参数

问题描述

使用 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。如果将来我添加更多这样的案例,它将无法正常工作。

标签: angularangular-routingurl-parameters

解决方案


尝试创建身份验证保护

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 之前执行检查,您可以稍后根据需要向其添加其他检查。


推荐阅读