【问题标题】:Angular routing: parameter in middle of string or after prefix角度路由:字符串中间或前缀之后的参数
【发布时间】:2020-06-18 22:15:57
【问题描述】:

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

【问题讨论】:

  • id不存在怎么办?比如 foo_666 和 666 不是有效的 id?
  • @Markus Dresch 这是在组件内部处理的,不是问题。
  • 那么在我看来处理组件内部的无效前缀将是一致的,而不是hacky。我不知道如何让路线按照你想要的方式工作。
  • @Markus Dresch 如果将来,如果我想除了 '/foo_123' 去MyAwesomeCompnent 添加路线 '/bar_acd' 去AnotherComponent 和 n像这样的其他情况。然后我必须从 MyAwesomeCompnent 重定向到 AnotherComponent 并从那里重定向到其他 N 个案例等等。这真的很丑陋。
  • 能否使用 CanActivate angular.io/api/router/CanActivate 来检查 id 的有效性并相应地进行路由?

标签: angular angular-routing url-parameters


【解决方案1】:

尝试创建身份验证保护

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] },

身份验证守卫将在加载 MyAwesomeComponent 之前执行检查,您可以稍后根据需要向其添加其他检查。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    相关资源
    最近更新 更多