角度路径参数中的前向斜率

Jon*_*gel 5 angular2-routing angular

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

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

这不起作用:

const SECTION_ROUTES: Routes = [
    { path: 'file/:path', component: FileStoreComponent }
];
Run Code Online (Sandbox Code Playgroud)

路由参数值是否可用?

我读过有关使用URL编码的URL方法.但是,我希望我的用户能够输入URL.

Thi*_* A. 6

要使用最新版本的 Angular(我的是 9.X)来实现此目的,您可以使用该Route.matcher参数。这是一个例子:

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 { }
Run Code Online (Sandbox Code Playgroud)

您将能够通过以下方式访问组件中的参数ActivatedRoute.paramMap

请注意,查询参数也有效并保留。

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

在这种情况下,您可以添加自定义 UrlSerializer来对括号进行编码,并且必须在组件中对它们进行解码。


Ste*_*ios 1

看起来您必须使用通配符转义每个正斜杠,如下所示:

/*page
Run Code Online (Sandbox Code Playgroud)

这个问题涵盖了它:Angular2 RouterLink Breaks paths by replacementlash with %2F

该问题链接到以下更深入​​的 GitHub 问题单: https: //github.com/angular/angular/issues/8049