在Angular JS中,识别上下文路径的更好方法是什么?



我有我的web应用程序部署到tomcat与应用程序上下文。例如,我的URL看起来像这样:

http://localhost:8080/myapp

myapp -是这里的应用程序上下文。

现在在一个Angular服务中,如果我想调用一个webservice,比如getusers。我的URL应该是/myapp/getusers。但是我希望避免对应用程序上下文进行硬编码,因为它可能在不同的部署之间发生变化。我已经设法从$window.location.pathname中找出了上下文路径,但它看起来非常愚蠢。有没有更好的办法?

仅供参考,我正在使用Spring MVC用于restful服务。

我所做的是在主jsp文件中声明一个变量。然后,该变量将在整个angular应用程序中可用。

<script type="text/javascript">
    var _contextPath = "${pageContext.request.contextPath}";
</script>

此代码应该在包含其他JavaScript库之前在header中编写。

我也使用tomcat和Spring MVC。在JavaScript中使用相对url可以达到这个目的。

要做到这一点,您只需要删除REST url开头的/。让你的url从浏览器中的当前url开始。

$resource('/getusers')替换为$resource('getusers')

向控制器注入$location服务

 var path = $location.path(); // will tell you the current path
     path = path.substr(1).split('/'); // you still have to split to get the application context
 // path() is also a setter
 $location.path(path[0] + '/getusers');
 // $location.path() === '/myapp/getusers'
 // ------------------ \
 // Shorter way
 $location.path($location.path() + '/getusers');
 // $location.path() === '/myapp/getusers'

在Angular 2中(如果使用hashbang模式)。下面的代码可以用来组成url:

document.location.href.substr(0, document.location.href.lastIndexOf("/#")) + "/getusers";

灵感来自@jarek-krochmalski的回答

如果你使用hashbang模式,使用"#",你可以这样做:

$location.absUrl().substr(0, $location.absUrl().lastIndexOf("#")) + "/getusers"

对于AngularJS $http服务,您可以使用url : 'getusers',如下所示:

$scope.postCall = function(obj) {
            $http({
                method : 'POST',
                url : 'getusers',
                dataType : 'json',
                headers : {
                    'Content-Type' : 'application/json'
                },
                data : obj,
            });
};

一般来说,你应该像这样在你的控制器中使用注入:

angular.module("yourModule").controller("yourController", ["$scope", "yourService", "$location", function($scope, yourService, $location){
....
      //here you can send the path value to your model.
      yourService.setPath($location.path());
....
}]);

最新更新