Arav Arav - 1 month ago 9
AngularJS Question

angular 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>

Answer

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

Comments