Angular应用中如何获取加载应用的完整URL
在Angular中获取应用的完整访问URL
你提到用Router或ActivatedRoute只能拿到路由路径,无法获取包含协议、域名的完整URL,这是因为Angular路由模块仅负责管理应用内部的路由路径,不涉及浏览器地址栏的协议、主机等全局信息。
以下是几种直接获取完整URL的方法:
方法一:直接使用window.location.href
这是最简单的方式,直接获取浏览器地址栏的完整URL:
ngOnInit() { const fullUrl = window.location.href; console.log(fullUrl); // 输出示例:https://localhost/blabla }
方法二:拆分拼接各部分URL信息
如果需要单独获取协议、主机、路径后再拼接,可以这样做:
ngOnInit() { const protocol = window.location.protocol; // 输出:"https:" const host = window.location.host; // 输出:"localhost" const path = window.location.pathname; // 输出:"/blabla" const fullUrl = `${protocol}//${host}${path}`; console.log(fullUrl); }
服务器端渲染(SSR)场景适配
如果你的应用使用SSR(比如Angular Universal),不能直接访问window对象,需要先判断当前运行环境:
import { Component, OnInit, Inject, PLATFORM_ID } from '@angular/core'; import { isPlatformBrowser } from '@angular/common'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html' }) export class YourComponent implements OnInit { constructor(@Inject(PLATFORM_ID) private platformId: Object) {} ngOnInit() { if (isPlatformBrowser(this.platformId)) { const fullUrl = window.location.href; console.log(fullUrl); } } }
内容的提问来源于stack exchange,提问作者chris01
相关产品推荐
相关产品推荐

