【问题标题】:Angular 5: Get host name and app name from URLAngular 5:从 URL 获取主机名和应用程序名称
【发布时间】:2018-08-24 03:49:36
【问题描述】:

我现在的网址是:

https://localhost:8080/MyApp/manager/dashboard

在上面的 url 中,我只想获取 https://localhost:8080/MyApp/ 部分。

有没有什么方法可以在不进行硬编码的情况下获取它?

【问题讨论】:

  • 这是业务规则吗?如果是这样,你能告诉我们它是什么吗?
  • @trichetriche,要求是仅从 url 获取主机名和应用程序名称。

标签: javascript angular typescript angular5


【解决方案1】:

window.location 包含大量信息。假设网址是 https://example.com:80/a/b/c,您可以在 Angular 中轻松获取以下信息:

window.location.hostname = "example.com"
window.location.host = "example.com:80"
window.location.protocol = "https:"
window.location.port = "80"
window.location.pathname = "/a/b/c"
window.location.href     = "https://example.com:80/a/b/c"

【讨论】:

    【解决方案2】:

    如果您只想获取域名和应用程序名称,请依赖路由器位置和窗口位置。

    import { Location } from '@angular/common';
    
    constructor(private loc: Location) {}
    
    ngOnInit() {
      const angularRoute = this.loc.path();
      const url = window.location.href;
    
      const domainAndApp = url.replace(angularRoute, '');
    }
    

    【讨论】:

    • Ty @user467634。建议:我会说const domainAndApp = url.replace(`#${angularRoute}`, '');更合适:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-13
    • 1970-01-01
    • 1970-01-01
    • 2012-09-16
    • 2012-03-26
    • 2019-06-05
    相关资源
    最近更新 更多