12

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

http://localhost:8080/myapp

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

如果我想调用网络服务,现在在 Angular 服务中说getusers。我的网址应该是这个/myapp/getusers。但我想避免对应用程序上下文进行硬编码,因为它可能会从一种部署更改为另一种部署。我已经设法从中找出上下文路径,$window.location.pathname但它看起来很愚蠢。有没有更好的办法?

仅供参考,我正在使用 Spring MVC 来提供宁静的服务。

4

7 回答 7

12

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

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

此代码应在包含其他 JavaScript 库之前写入标头中。

于 2013-09-02T14:54:07.667 回答
7

我也在使用 tomcat 和 Spring MVC。在 JavaScript 中使用相对 url 就可以了。

为此,您只需删除/REST url 开头的 。这样您的 url 从浏览器中的当前 url 开始。

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

于 2015-06-16T12:14:41.020 回答
3

将$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'
于 2013-06-10T15:21:03.000 回答
2

在 Angular 2 中(如果使用 hashbang 模式)。下面的代码可用于形成 url。

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

灵感来自@jarek-krochmalski 的回答

于 2017-12-28T18:05:33.153 回答
1

如果您使用的是 hashbang 模式,带有“#”,您可以执行以下操作:

$location.absUrl().substr(0, $location.absUrl().lastIndexOf("#")) + "/getusers"
于 2013-12-10T10:00:45.890 回答
1

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

$scope.postCall = function(obj) {
            $http({
                method : 'POST',
                url : 'getusers',
                dataType : 'json',
                headers : {
                    'Content-Type' : 'application/json'
                },
                data : obj,
            });
};
于 2017-03-17T10:41:22.050 回答
0

通常,您应该在控制器中使用注入,如下所示:

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());

....

}]);
于 2017-08-20T02:38:41.797 回答