Angular 2中如何从RouterStateSnapshot获取目标路由的绝对URL?
在Angular中从RouterStateSnapshot获取目标路由的绝对URL
我完全懂你想要的效果——就像AngularJS UI-Router里的$state.href(toState, toParams, { absolute: true })那样,拿到完整的绝对URL而非相对路径对吧?这有两种靠谱的方法可以实现,而且都能满足你传给非Angular代码的需求:
方法一:结合Router和Location服务(推荐,符合Angular依赖注入规范)
这种方法不直接依赖全局window对象,更符合Angular的最佳实践。首先你需要在组件/服务中注入Router和Location,然后通过RouterStateSnapshot生成对应的绝对URL:
import { Router, RouterStateSnapshot, Location } from '@angular/router'; // 在组件或服务的构造函数中注入依赖 constructor(private router: Router, private location: Location) {} // 定义获取绝对URL的方法 getTargetAbsoluteUrl(state: RouterStateSnapshot): string { // 基于目标路由状态生成URL树并序列化为相对路径字符串 const relativePath = this.router.serializeUrl( this.router.createUrlTree([], { relativeTo: state.root }) ); // 拼接origin(比如http://localhost:4200)和相对路径,得到完整绝对URL return `${this.location.origin}${relativePath}`; }
方法二:直接使用全局window对象(简单快捷)
如果你只是在组件中临时使用,不想额外注入服务,也可以直接用window.location.origin配合RouterStateSnapshot的url属性:
getTargetAbsoluteUrl(state: RouterStateSnapshot): string { return `${window.location.origin}${state.url}`; }
用法示例(比如在路由守卫中)
假设你在CanActivate守卫里需要获取目标路由的绝对URL,就可以这样调用:
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { const absoluteUrl = this.getTargetAbsoluteUrl(state); // 把absoluteUrl传给你的非Angular代码 console.log(absoluteUrl); // 输出类似 http://localhost:4200/product return true; }
这两种方法都能帮你拿到完整的绝对URL,完全替代AngularJS里$state.href的absolute: true用法,完美适配你的需求~
内容的提问来源于stack exchange,提问作者user911
相关产品推荐
相关产品推荐

