$ http使用$ q完成函数

时间:2015-02-16 14:27:57

标签: angularjs

我想使用延迟承诺在angularjs中使用某些东西。这样当我的$ http请求完成时我可以使用then条件。我最后尝试了但是代码无效并且在错误阻止之后总是没有工作。

userApp.runMachineLearning = function($scope, $http, $rootScope, $route, $q) {
$scope.objRun = {};
$scope.loader = {
    loading : false
};

deferred=$q.defer();

$scope.runMachine = function(objRun) {

    $scope.loader.loading = true;


        $scope.objRun = objRun;
        $scope.method = 'POST';
        console.log("Call");

        $scope.url = 'rest/service/pipeline/runMachineLearning';

        $http({
            method : $scope.method,
            url : $scope.url,
            data : $scope.objRun,
            headers : {
                'X-Auth-Token' : $rootScope.authToken
            }
        }).success(function(data, status) {
            $scope.status = status;
            $scope.data = data;
        }).error(function(data, status) {
            $scope.data = data || "Request failed";
            $scope.status = status;
        }).then(function(data) {
          console.log("Complete Message");
        });

};
};

2 个答案:

答案 0 :(得分:0)

您使用了$ http服务返回的promise对象。 你没有使用你的deffered对象,看起来你不需要,首先让我们看看你应该使用$ http promise的方式。

当你得到承诺时,你有2种方法来处理它:

  1. 常规然后方法 - 然后(successCallback,errorCallback,notifyCallback)

    promise.then(function(greeting) {
      alert('Success: ' + greeting);
    }, function(reason) {
      alert('Failed: ' + reason);
    });
    
  2. 成功\错误

    $http.post('/someUrl', {msg:'hello word!'}).
    success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available
      }).
      error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
      });
    
  3. 在你的情况下你使用了两个+没有正确使用。 以下是promises$http

    的angularjs文档

答案 1 :(得分:0)

将控制器和服务分开是个好主意。控制器仅设置视图附加到的视图模型。服务是执行http调用并将业务逻辑应用于数据的东西。

如果我使用控制器和服务写出你的实现,它将大致如下:

angular.module('machineLearning', [])
  .factory('authService', ['$rootScope', authService])
  .factory('runMachineLearningService', ['$http', 'authService', runMachineLearningService])
  .controller('runMachineLearningCtrl', ['$scope', 'runMachineLearningService', runMachineLearningCtrl])

function authService() {
  var service = {
    getAuthToken: getAuthToken
  };

  return service;

  function getAuthToken(){
    // some implementation that returns the auth token
  }
}

function runMachineLearningService($http, authService){
  var service = {
    run: run
  };

  var serviceBase = 'rest/service/pipeline/runMachineLearning';

  return service;

  function run(objRun){
    return $http.post(serviceBase, objRun, {
        headers : {
            'X-Auth-Token': authService.getAuthToken
        }
    }).then(function (data) {
      return data.data;
    }).catch(function (message) {
      // do something with this error.
    });
  }
}

function runMachineLearningCtrl($scope, runMachineLearningService) {
  $scope.objRun = {};
  $scope.loader = {
      loading : false
  };

  $scope.runMachine = function(objRun) {
    runMachineLearningService.run(objRun)
      .success(function(data, status) {
          $scope.status = status;
          $scope.data = data;
      }).error(function(data, status) {
          $scope.data = data || "Request failed";
          $scope.status = status;
      }).then(function(data) {
        console.log("Complete Message");
      });

  };
}

这样做的好处是:

  • 良好的关注点分离
  • 最小化传递给控制器​​的依赖关系链的大小
  • 易于维护

所有这些都是有助于更轻松,更好地维护和/或调试角度代码库的好东西。

我的代码中需要注意的一些事项:

    从服务返回
  • $http,可以多次访问then函数,这允许您创建一个promises管道,每个都可以修改您的数据。它允许您在服务中使用错误日志记录和正常日志记录服务,使它们不受控制器的影响
  • AuthService从所有内容中抽象出授权逻辑,因此可以在应用程序的其余部分重用它。
  • 在控制器中,可以更容易地看到正在发生的事情,因为代码没有被auth样板或$http样板代码污染。

至于理解$q库和$http它的好处就是从它们开始。

  • $q是一个帮助异步回调的实现,它为您提供了可以在将来某个时候解决或拒绝的承诺。当返回此promise时,它会公开一些在解析或拒绝时将执行的函数。
  • $http是一项服务,可以更轻松地进行AJAX调用,实现 $q

这意味着,您不需要将$q$http一起使用,以便利用AJAX调用的异步性。