You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 16:28:11