Whats the better way to identify the context path in Angular JS

后端 未结 7 1043
清酒与你
清酒与你 2021-02-05 20:38

I have my web application deployed to tomcat with an applicatio context. For example my URL looks something like this.

http://localhost:8080/myapp
相关标签:
7条回答
  • 2021-02-05 21:00

    Inject the $location service to your controller.

     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'
    
    0 讨论(0)
  • 2021-02-05 21:03

    For AngularJS $http service you are good to go with url : 'getusers', as follows:

    $scope.postCall = function(obj) {
                $http({
                    method : 'POST',
                    url : 'getusers',
                    dataType : 'json',
                    headers : {
                        'Content-Type' : 'application/json'
                    },
                    data : obj,
                });
    };
    
    0 讨论(0)
  • 2021-02-05 21:06

    In general, you should use injection in your controller like the following:

    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());
    
    ....
    
    }]);
    
    0 讨论(0)
  • 2021-02-05 21:07

    What I have done is declared a variable in the main jsp file. Then that variable will be available throughout the angular application.

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

    This code should be written in header before including other JavaScript libraries.

    0 讨论(0)
  • 2021-02-05 21:07

    I'm also using tomcat and Spring MVC. Using relative url in JavaScript will do the trick.

    For doing this you just need to remove the / at the begining of REST url. so that your url starts from the current url in your browser.

    replace $resource('/getusers') with $resource('getusers')

    0 讨论(0)
  • 2021-02-05 21:21

    if you are using hashbang mode, with "#", you can do something like that:

    $location.absUrl().substr(0, $location.absUrl().lastIndexOf("#")) + "/getusers"
    
    0 讨论(0)
提交回复
热议问题