Angular Route 参数中的正斜杠 [英] Forward Slash in Angular Route Parameters

查看:28
本文介绍了Angular Route 参数中的正斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何设置我的路由,以便我的参数可以使用正斜杠?

How do I set up my routes so that my parameter can take forward slashes?

例如:myapp.com/file/rootfolder/subfolder/myfile

For example: myapp.com/file/rootfolder/subfolder/myfile

这不起作用:

const SECTION_ROUTES: Routes = [
    { path: 'file/:path', component: FileStoreComponent }
];

是否可以在路由参数值中使用/?

Is having / in routing parameter values possible?

我已经阅读了使用 URL 编码的 URL 方法.但是,我希望我的用户能够输入 URL.

I've read about URL approaches that use URL encoding. However, I'd like my user to be able to type the URL.

推荐答案

要使用最新版本的 Angular(对我来说是 9.X)来实现这一点,您可以使用 Route.matcher 参数.下面是一个例子:

To achieve this with a recent version of Angular (9.X for me), you can use the Route.matcher parameter. Here is an example:

function filepathMatcher(segments: UrlSegment[], 
                         group: UrlSegmentGroup, 
                         route: Route) : UrlMatchResult {
  // match urls like "/files/:filepath" where filepath can contain '/'
  if (segments.length > 0) {
    // if first segment is 'files', then concat all the next segments into a single one
    // and return it as a parameter named 'filepath'
    if (segments[0].path == "files") {
      return {
        consumed: segments,
        posParams: {
          filepath: new UrlSegment(segments.slice(1).join("/"), {})
        }
      };
    }
  }
  return null;
}

const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { matcher: filepathMatcher, component: FilesComponent },
  // ...
];

@NgModule({
  imports: [RouterModule.forRoot(routes, { useHash: true })],
  exports: [RouterModule]
})
export class AppRoutingModule { }

您将能够通过 ActivatedRoute.paramMap

请注意,查询参数也有效并保留了下来.

Note the query parameters are also working and preserved.

但是,如果 URL 包含括号,您仍然会遇到问题,例如 /files/hello(world:12)/test 因为它们被 angular 解释为辅助路由

However, you will still have issues if the URL contains parenthesis, for example /files/hello(world:12)/test because they are interpreted by angular as auxiliary routes

在这种情况下,您可以添加一个自定义 UrlSerializer编码括号,你必须在你的组件中解码它们.

In this case, you can add a custom UrlSerializer to encode parenthesis and you'll have to decode them in your Component.

这篇关于Angular Route 参数中的正斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆