1

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>
Arav
  • 4,957
  • 23
  • 77
  • 123

1 Answers1

2

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

nikjohn
  • 20,026
  • 14
  • 50
  • 86
  • Thanks for the info. Will you be able to help me out this query http://stackoverflow.com/questions/40231503/dynamic-html-angular-js – Arav Oct 26 '16 at 04:52