AngularJS 承诺的 $http 结果

AngularJS $http result with promise

我是 angular $q service.I 的新人,正在使用 $http 和 angular $q用于实现异步请求的服务。下面是我的代码,我无法获得后端 api 的结果。 (json)

Services.js :

.service('httpService', function($q, $http, $timeout) {

 var asyncRequest = function(url) {
    return $http.get(url)
        .then(function(response) {
            //res is the index of an array in php, which will be encoded.
            return response.res;

        }, function(response) {
            // something went wrong
            return $q.reject(response.res);
        });
 };
 return {
   asyncRequest : asyncRequest 
 };

});

Controller.js :

var result = httpService.test(url)
.then(function(data) {
    // Line below gives me "undefined"
    console.log(data);
}, function(error) {
    alert("Error...!");
});

提到的行,给我未定义。 (当然,我可以在main函数中写console.log(data),但这不是一个好的做法,因为我想return result to controller

关于我实现的$q服务,有没有更简单的方法?

任何想法将不胜感激。

在这种情况下,您应该使用$q,因为$http已经returns一个承诺。一起使用 to 2 效率低下。 ($q 在您使用非 angular 异步函数时有用,例如地理查找)。

Services.js :

.service('httpService', function($http, $timeout) {

  var asyncRequest = function(url) {
    return $http.get(url)
  };
  return {
   asyncRequest : asyncRequest 
  };

});

Controller.js :

var result = httpService.asyncRequest(url)
.then(function(res) {
    console.log(res.data);
}, function(error) {
    alert("Error...!");
});
.service('httpService', function($q, $http, $timeout) {

 var asyncRequest = function(url) {
   var defer = $q.defer();
    return $http.get(url)
        .then(function(response) {
            //res is the index of an array in php, which will be encoded.
            defer.resolve(response);

        }, function(response) {
            // something went wrong
            defer.reject(response.res);
        });
     return defer.promise;
 };
 return {
   asyncRequest : asyncRequest 
 };

});

你应该return像这样从你的对象中承诺

第一件事是你使用的是工厂风格而不是服务。服务只是一个函数,其中的方法在 this 参考中定义。

我认为您不需要在服务中使用 .then 只需 return 承诺 return 由 $http

编辑
app.service('httpService', function($q, $http, $timeout) {

  this.asyncRequest = function(url) {
    return $http.get(url);
  };
});

并在控制器中

 var result = httpService.test(url)
  .then(function(res) {
    // Line below gives me "undefined"
    console.log(res.data);
  }, function(error) {
    alert("Error...!");
  });

我认为您在服务中使用的是 at factory 语法。

.service('httpService', function($q, $http, $timeout) {
   this.asyncRequest = function(url) {};
});

.factory('httpService', function($q, $http, $timeout) {
   return {asyncRequest: function(url) {}};
});

响应已在上述行中被拒绝。你不需要拒绝任何其他东西。所以你不需要 $q.

首先你已经return一个承诺。您可以在控制器中通过添加 success()error() 承诺的 $http 委托来处理它。 其次,这是异步操作。而且您不能 return 来自成功回调的响应,例如 jQuery.ajax()。这不是同步调用,这是异步调用,您必须使用回调。你的错误就在这里。只需 return 承诺并在响应已被解决或拒绝时在控制器中处理它。

所以你的控制器代码可以是这样的:

httpService.asyncRequest({
    ...
}).success(function(successfulResponse) {
    ...
}).error(function(failedResponse) {
    ...
});