如何从其他控制器调用$http.post

How to call $http.post from other controller?

本文关键字:http post 调用 控制器 其他      更新时间:2023-09-26

我下面有这个控制器。页面加载后,将执行您在下面看到的$http服务。

现在,我如何从其他控制器再次调用并执行控制器的$http.post(…)部分。


 controller: function ($scope, $element, $http) {
    function par() {               
        var xxx= null;
        xxx = $scope.$parent.$root.ParentItems['xxx'].xxx;
        var det = { xxx: xxx};              
        return det;
    }

 $http.post('/api/values/entries/GoHere', par()).success(function (salData) {
      var buildSHGraph = function (shData) {
        //code code codes...
      }
      $scope.Array1 = [];
      angular.forEach(salData, function (evt) {
         //Code Code Codes
      });
     buildSHGraph($scope.Array1);
 });
 }

您可以创建共享服务

angular.module("yourAppName", []).
    factory("mySharedService", ['$http', function($http){
        return {
           callPost: function(params) {
               return $http.post('/api/values/entries/GoHere', params)
                    .success()
                    .error();
           }
        };
}]);

然后将其注入任何控制器并调用必要的服务方法。

function FirstController($scope, mySharedService) {
    $scope.params = {//..//};
    $scope.result1 = mySharedService.callPost(params)
                    .success(function(result){//..//});  
}
function SecondController($scope, mySharedService) {
    $scope.params = {//..//};
    $scope.result2 = mySharedService.callPost(params)
                    .success(function(result){//..//});  
}