Javascript 在 AngularJS 中获取基本 url
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35097113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get base url in AngularJS
提问by alex
I want to get the base path of my Angular app.
我想获取我的 Angular 应用程序的基本路径。
Right now I'm doing this: $scope.baseUrl = '$location.host()
现在我正在这样做: $scope.baseUrl = '$location.host()
But I only get this: /localhost
. My current baseURL is http://localhost:9000/
.
但我只得到这个:/localhost
. 我当前的 baseURL 是http://localhost:9000/
.
采纳答案by Leon Gaban
Try this: $location.$$absUrl
尝试这个: $location.$$absUrl
console.log('$location',$location.$$absUrl);
console.log('$location',$location.$$absUrl);
btw /localhost
is your base path, but I guess you meant entire URL.
顺便说一句,/localhost
是您的基本路径,但我猜您的意思是整个 URL。
回答by Zach Nagatani
An alternative answer is using the $window
service in conjunction with $location.absUrl()
to create a new URL object, and then grab the origin via the origin property. This will give you exactly what you're looking for (minus the trailing '/').
另一个答案是$window
结合使用该服务$location.absUrl()
来创建一个新的 URL 对象,然后通过 origin 属性获取源。这将为您提供您正在寻找的内容(减去尾随的“/”)。
$scope.baseUrl = new $window.URL($location.absUrl()).origin;
will give you back http://localhost:9000in your case.
$scope.baseUrl = new $window.URL($location.absUrl()).origin;
在你的情况下会给你http://localhost:9000。
回答by el-davo
To get just the baseurl and nothing else use
只获取 baseurl 而没有其他用途
$browser.baseHref()
it will return something like
它会返回类似的东西
/central/
/中央/
回答by Kesarion
A cross browser solution that worked for me was:
对我有用的跨浏览器解决方案是:
$location.$$absUrl.replace($location.$$url, '')
$$absUrl
is the entire url (e.g. https://google.com/search/spiders)
$$absUrl
是整个网址(例如https://google.com/search/spiders)
$$url
is the part after the host (e.g. /search/spiders)
$$url
是主机后面的部分(例如/search/spiders)
Modify to taste.
根据口味修改。
回答by Ben Glasser
try injecting $location
it has an absUrl()
method on it that will return the entire current url
尝试注入$location
它有一个absUrl()
方法,它将返回整个当前 url
回答by Sylvan D Ash
If you only want to get the base url of the site, and not the current url of the page, e.g. from https://www.google.com/somewhere/in-the-middle-of-nowhere
you want to get https://www.google.com
, then simply do:
如果您只想获取站点的基本 url,而不是页面的当前 url,例如从https://www.google.com/somewhere/in-the-middle-of-nowhere
您想获取https://www.google.com
,那么只需执行以下操作:
// For www.google.com
$scope.baseUrl = $locaton.$$host;
// For https://www.google.com
$scope.baseUrl = $location.$$protocol + '://' + $location.$$host;
回答by Sai Hanuman
Instead of using $scope.baseUrl = '$location.host()
而不是使用 $scope.baseUrl = '$location.host()
Use this one :-
使用这个:-
$scope.baseUrl = $location.absUrl();