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

dar*_*isa 12 spring-mvc contextpath angularjs

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

http://localhost:8080/myapp
Run Code Online (Sandbox Code Playgroud)

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

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

仅供参考我使用Spring MVC来提供宁静的服务.

小智 12

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

<script type="text/javascript">
    var _contextPath = "${pageContext.request.contextPath}";
</script>
Run Code Online (Sandbox Code Playgroud)

在包含其他JavaScript库之前,应该在头文件中编写此代码.


Qia*_*ong 6

我也在使用tomcat和Spring MVC.在JavaScript中使用相对URL将起到作用.

为此,您只需要/在REST URL的开头删除它.这样您的网址就会从浏览器中的当前网址开始.

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


Oli*_*ver 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'
Run Code Online (Sandbox Code Playgroud)

  • 如果您在非单页应用程序中使用 Angular,则此方法不可靠。例如调用 ${contextPath}/api/delegation/apps。上面的方法不知道应用程序是否已重新部署到根上下文或从各种嵌套路径调用页面。 (5认同)