AngularJS,从服务中捕获响应并在控制器中使用它

时间:2016-07-07 21:08:59

标签: angularjs angularjs-service angularjs-controller

我已经创建了一个服务并且我有一个响应,但我不知道如何将该响应用于控制器。

我所拥有的服务:

angular
.module('MyApp')
.service('telForm', function($http){
  this.getAll = function(success, failure){
      $http.get('https://service.com.mx/telehone')
        .success(success)
        .error(failure);
  }
})
// the answer is 
{
"telehone": "12121212",
"token": "760619"
}

我想要构建的控制器:(更无)

var1 = "telephone";
var2 = "token";

$http({
    method:'POST',
    url:"http://www.example-server.com/" + telephone + "/" + token + "/example",
    data : {
      phone: $scope.phone,
      company: $scope.company,
      contract: '1',
      privacy: '1',
      email: $scope.email
    },
    headers: {
        'Content-Type': 'application/json'
    }
})

提前致谢

2 个答案:

答案 0 :(得分:2)

首先,不推荐使用方法successerror,因为您可以查看deprecation notice

  

弃用通知

     

已弃用$http遗留承诺方法successerror。请改用标准then方法。如果$httpProvider.useLegacyPromiseExtensions设置为false,则这些方法会抛出$http/legacy错误。

您只需从服务中返回承诺,然后在控制器中执行您想要的操作,如下所示:

(function() {
  "use strict";
  angular.module('app', [])
    .controller('mainCtrl', function($scope, telForm) {
      $scope.response = '';
      $scope.doGet = function() {
        telForm.doGet().then(
          function(response) {
            $scope.response = 'success';
            // $scope.services = response.data;
          },
          function(response) {
            $scope.response = 'error';
          });
      }

      $scope.doPost = function() {
        $http({
          method: 'POST',
          url: "http://www.example-server.com/" + telephone + "/" + token + "/example",
          data: {
            phone: $scope.phone,
            company: $scope.company,
            contract: '1',
            privacy: '1',
            email: $scope.email
          },
          headers: {
            'Content-Type': 'application/json'
          }
        });
      }
    })

  .service('telForm', function($http) {
    function doGet() {
      // return promise from test
      return $http.get('http://api.geonames.org/citiesJSON?');
    }

    return {
      doGet: doGet
    }
  })
})();
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>

<body ng-controller="mainCtrl">
  Response: <span ng-bind="response"></span>
  <hr>
  <button type="button" ng-click="doGet()">Request</button>
</body>

</html>

答案 1 :(得分:0)

尝试这样的事情

.service('myService', ['$http', function ($http) {
    var getAll = function (url, callback) {
        $http.get(url)
            .success(function (response) {
                callback(response);
            })
            .error(function (err) {
                callback(err);
            })
    }
    return {
        getAll:getAll
    }
}]);

然后在您的控制器中,您可以像这样调用服务

.controller('myController', ['myService', function (myService) {
    myService.getAll('http://...', function (response) {
            // do something with the response
        })

}]);