如何优雅地从 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
的一个实例.
The route
parameter is an instance of 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 router 没有现成的函数来实现这一点,所以我写了它们:
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
时的示例输出:
Example output when route
is from ProjectComponent
:
const routes: Routes = [
{
path: 'project', component: ProjectListComponent, children: [
{path: ':id', component: ProjectComponent}
]
},
];
getResolvedUrl(route) => /project/id1
getConfiguredUrl(route) => /project/:id
这篇关于如何优雅地从 ActivatedRouteSnapshot 获取完整 url?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!