简体   繁体   中英

AngularJS route provider - post request

How can I do a post request to a url using routeprovider? Provided sample code below

<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
    $routeProvider
    .when("/", {
        templateUrl : "main.htm"
    })
    .when("/red", {
        templateUrl : "red.htm"
    })
    .when("/green", {
        templateUrl : "green.htm"
    })
    .when("/blue", {
        templateUrl : "blue.htm"
    });
});
</script>

You can use a resolve :

.when("/", {
    templateUrl : "main.htm",
    resolve: {
      data: function($http) {
        $http.post('/yourUrl', yourData)
            .then(function(res) {
              return res;
            }, function(err) {
              console.log(err);
              return null;
            })
    }
    }
})

And then in your controller,

.controller(function(data) {
   console.log(data);
 })

NOTE: This is not using routeProvider per se, because making REST calls is not what the routeProvider is for. Angular can do that only through the $http service. I am assuming that you just want to make a REST call from within your route definition.

Protip A better way of doing this would be to define a service in your module, and insert the module in the route resolve, rather than injecting $http directly. I've done that here only for brevity

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM