如何优雅地从ActivatedRouteSnapshot获取完整的URL? [英] How to elegantly get full url from the ActivatedRouteSnapshot?
问题描述
在某些Angular路由防护中,我想设置下一条"路径,以便在成功登录后重定向到该路径.
In some of my Angular route guards, I want to set up the "next" path, to redirect to after successful login.
因此,普通后卫canActivate
函数签名如下:
So, the ordinary guard canActivate
function signature looks like this:
public canActivate(route: ActivatedRouteSnapshot): Observable<boolean> | boolean {
// ...blah
return true;
}
route
参数是ActivatedRouteSnapshot
的实例.
以前,要获取下一个" URL,我只是从route.url
获取它.只要没有子路线,此方法就可以正常工作.
Previously to get the "next" URL I was just getting it from the route.url
. This works just fine, as long as there are no children routes.
我的示例URL是/search/advanced?query_hash=1221d3b57f5616ee16ce70fdc78907ab
,其中advanced
是search
的子路由.
My example URL is /search/advanced?query_hash=1221d3b57f5616ee16ce70fdc78907ab
, where advanced
is a child route of a search
.
子路径可以在route.children
中找到,但是在这些子路径上进行迭代(尤其是可能存在多个级别),并且以这种方式组合URL似乎很尴尬和丑陋.
Child routes can be found in route.children
, but iterating over these children (especially there might be multiple levels) and combining the URL this way seems awkward and ugly.
我感兴趣的内容包含在route._routerState.url
属性中(是字符串,在下图的底部),但这是一个私有"变量.
What I'm interested in is contained in route._routerState.url
property (being a string, on the bottom of the image below), but it's a "private" variable.
我错过了什么吗?如何从ActivatedRouteSnapshot
优雅地获取完整的(带有子路径)URL? Angular版本为5.1.
Am I missing something? How can one elegantly get the full (with children paths) URL from the ActivatedRouteSnapshot
? Angular version is 5.1.
推荐答案
Angular路由器尚无法使用现成的功能来实现该功能,所以我写了它们:
There's no ready to use function from Angular router to achieve that, so I wrote them:
function getResolvedUrl(route: ActivatedRouteSnapshot): string {
return route.pathFromRoot
.map(v => v.url.map(segment => segment.toString()).join('/'))
.join('/');
}
function getConfiguredUrl(route: ActivatedRouteSnapshot): string {
return '/' + route.pathFromRoot
.filter(v => v.routeConfig)
.map(v => v.routeConfig!.path)
.join('/');
}
route
来自ProjectComponent
时的示例输出:
const routes: Routes = [
{
path: 'project', component: ProjectListComponent, children: [
{path: ':id', component: ProjectComponent}
]
},
];
getResolvedUrl(route) => /project/id1
getConfiguredUrl(route) => /project/:id
这篇关于如何优雅地从ActivatedRouteSnapshot获取完整的URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!