如何从angular $location获取host+base



我有一个angular应用程序位于目录'someApp'。对于路径为http://example-domain/someApp/#/user/login的状态Url, Url为http://example-domain/someApp/#/。我有"角度的方式"得到这个部分http://example-domain/someApp/

var redirectUri = $location.absUrl();
redirectUri = redirectUri.substr(0, redirectUri.indexOf('#'));

最简单的方法是使用

window.location.origin + window.location.pathname

返回http://example-domain/someApp

这将提供整个基本url,即使使用虚拟目录/路径。但是,IE不支持origin。因此,您可以将url的组件连接起来,以提供基本目录,如下所示:

window.location.protocol + "//" + window.location.hostname + window.location.pathname

返回http://example-domain/someApp

如果使用虚拟目录,您将很难使用$location,因为$location.path()返回AFTER散列,而$location.host()只返回域,而不是域和目录,这是window.location.hostname + window.location.pathname给您的。

您需要使用:

 location.origin + location.pathname

假设url是http://example.com/#/some/path?foo=bar&baz=xoxo

$location.protocol(); // will give: http
$location.host();     // will give: example.com
location.host         // will give: example.com:8080
$location.port();     // will give: 8080
$location.path();     // will give: /some/path
$location.url();      // will give: /some/path?foo=bar&baz=xoxo

查看详细信息

location.hash      ➡️ #/some/path
location.protocol; ➡️ http: or https:
location.hostname; ➡️ example.com
location.host;     ➡️ example.com:8080
location.port;     ➡️ 8080
location.href;     ➡️ http://example.com:8080/#/some/path
location.origin;   ➡️ http://example.com:8080
location.path;     ➡️ /

最新更新