AngularJS $ http带有promise的结果

Vah*_*afi 2 javascript asynchronous angularjs q angular-promise

我是角度$ q服务的新手.我正在使用$http角度$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 
 };

});
Run Code Online (Sandbox Code Playgroud)

Controller.js:

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

提到的行,给我未定义.(当然,我可以在main函数中编写console.log(data),但这不是一个好习惯,因为我想将结果返回给控制器)

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

任何想法将不胜感激.

Sim*_*n H 5

你应该使用$q在这种情况下,作为$http已经返回一个承诺.使用2一起效率低下.($q如果您使用的是非角度异步函数,则可以使用,例如地理查找).

Services.js:

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

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

});
Run Code Online (Sandbox Code Playgroud)

Controller.js:

var result = httpService.asyncRequest(url)
.then(function(res) {
    console.log(res.data);
}, function(error) {
    alert("Error...!");
});
Run Code Online (Sandbox Code Playgroud)