AngularJS $http 结果与承诺 [英] AngularJS $http result with promise

查看:30
本文介绍了AngularJS $http 结果与承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new in angular $q service.I'm using $http with angular $q service for implementing asynchronous requests. Here in below is my codes which I can't get the result of backend 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),但这不是一个好习惯,因为我想把结果返回给控制器)

The mentioned line, gives me undefined. (Of course, I can write console.log(data) in main function, But it's not a good practice, because I want to return result to controller)

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

About my implementation of $q service, is there any easier way?

任何想法将不胜感激.

推荐答案

你应该不要在这种情况下使用 $q,如 $http 已经返回了一个承诺.一起使用 2 效率低下.($q 在您使用非角度异步函数时很有用,例如地理查找).

You should not use $q in this instance, as $http already returns a promise. Using to 2 together in inefficient. ($q is of use if you are using a non-angular async function, such as a Geo lookup).

Services.js:

Services.js :

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

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

});

Controller.js :

Controller.js :

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

这篇关于AngularJS $http 结果与承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆