简体   繁体   English

AngularJS路由提供者-发布请求

[英]AngularJS route provider - post request

How can I do a post request to a url using routeprovider? 我如何使用routeprovider向URL发送请求? 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 : 您可以使用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. 注意:这本身不使用routeProvider ,因为进行REST调用不是routeProvider的用途。 Angular can do that only through the $http service. Angular只能通过$http服务来做到这一点。 I am assuming that you just want to make a REST call from within your route definition. 我假设您只想从路由定义中进行REST调用。

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. Protip一种更好的方法是在模块中定义一个服务,然后将该模块插入路由解析中,而不是直接注入$http I've done that here only for brevity 我这样做只是为了简洁

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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