如何设置我的路线,以便我的参数可以采用正斜杠?
例如:myapp.com/file/rootfolder/subfolder/myfile
这不起作用:
const SECTION_ROUTES: Routes = [
{ path: 'file/:path', component: FileStoreComponent }
];
路由参数值中可以有 / 吗?
我读过有关使用 URL 编码的 URL 方法的信息。但是,我希望我的用户能够输入 URL。
要使用最新版本的 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 { }
您将能够通过以下方式访问组件中的参数ActivatedRoute.paramMap
请注意,查询参数也有效并保留。
但是,如果 URL 包含括号,您仍然会遇到问题,例如/files/hello(world:12)/test
因为它们被 Angular 解释为辅助路线
在这种情况下,您可以添加一个自定义 UrlSerializer要对括号进行编码,您必须在组件中对它们进行解码。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)