使用.then方法解析时,未定义的$ http数据 [英] Undefined $http data when resolved with `.then` method

查看:484
本文介绍了使用.then方法解析时,未定义的$ http数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了控制台日志,该日志返回了从服务器获取的数据数组,但是当我在html上调用作用域时,在控制台上出现了未定义的错误.

I used the console log which returned the array of data fetched from the server, but when I call the scope on the html I get an undefined error on the console.

app.service('blogpostservice', ['$http', function ($http) {
    this.getMoreData = function (pagecount) {
        return $http.get('/api/posts/' + pagecount);
    }
}]);
app.controller('MainController', ['$scope', 'blogpostservice',
    function ($scope, blogpostservice) {
        $scope.pagec = 1;
        this.getMoreData = function () {
            blogpostservice.getMoreData($scope.pagec).then(function (data) {
                $scope.posts = data;
                console.log($scope.posts);

            })
        }

        this.getMoreData();

    }]);

HTML

 <h1>{{pagec}}</h1>
    <h1>{{posts[1].Title}}</h1>
    <div id="posts" class="grid" ng-repeat="post in posts">
         <div class=" grid-item">
              <div class="blog-post">
                  <img src="https://placeimg.com/400/400/bbc" alt="">
                  <h3>{{post.Title}}</h3>
                  <img ng-src="{{post.Image}}" alt="">         
               </div>
          </div>
    </div>

推荐答案

$http承诺的.then方法返回一个response对象,其中data是下列属性之一:

The .then method of an $http promise returns a response object, of which data is one of several properties:

app.service('blogpostservice', ['$http', function ($http) {
    this.getMoreData = function (pagecount) {
        return $http.get('/api/posts/' + pagecount);
    }
}]);

app.controller('MainController', ['$scope', 'blogpostservice',
    function ($scope, blogpostservice) {
        $scope.pagec = 1;
        this.getMoreData = function () {
            blogpostservice.getMoreData($scope.pagec)
              ̶.̶t̶h̶e̶n̶(̶f̶u̶n̶c̶t̶i̶o̶n̶ ̶(̶d̶a̶t̶a̶)̶ ̶{̶
              .then(function (response) { 
                ͟v͟a͟r͟ ͟d͟a͟t͟a͟ ͟=͟ ͟r͟e͟s͟p͟o͟n͟s͟e͟.͟d͟a͟t͟a͟;͟
                $scope.posts = data;
                console.log($scope.posts);    
            })
              .catch(function(response) {
                console.log("Error: ", response.status);
                throw response;
            });
        };    
        this.getMoreData();    
    }      
]);

还要确保添加.catch处理程序以记录被拒绝的http请求.

Also be sure to add a .catch handler to log rejected http requests.

有关更多信息,请参见 AngularJS $ http服务API参考.

For more information, see AngularJS $http Service API Reference.

我阅读了文档,但连接到主题后,我遇到的主要问题是将其称为数据而不是对函数的响应?

i read the doc but connecting to the subject the main problem i made is calling it a data instead of a response on the function right?

主要问题是http承诺不能解决data .它解析 response对象. Data只是response对象的属性之一:

The main problem is that the http promise does not resolve data. It resolves a response object. Data is only one of the properties of the response object:

$http(...)
  .then(function onSuccess(response) {
    // Handle success
    var data = response.data;
    var status = response.status;
    var statusText = response.statusText;
    var headers = response.headers;
    var config = response.config;
    ...
  })
  .catch(function onError(response) {
    // Handle error
    var data = response.data;
    var status = response.status;
    var statusText = response.statusText;
    var headers = response.headers;
    var config = response.config;
    ...
  });

从文档中:

响应对象具有以下属性:

The response object has these properties:

  • data – {string|Object} –使用转换函数转换的响应主体.
  • 状态-{number}-响应的HTTP状态代码.
  • 标题– {function([headerName])} –标题获取器功能.
  • config – {Object} –用于生成请求的配置对象.
  • statusText – {string} –响应的HTTP状态文本.
  • xhrStatus – {string} – XMLHttpRequest的状态(completeerrortimeoutabort).
  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.
  • xhrStatus – {string} – Status of the XMLHttpRequest (complete, error, timeout or abort).

200到299之间的响应状态代码被视为成功状态,并且将导致调用成功回调.任何超出该范围的响应状态代码均被视为错误状态,并会导致错误回调被调用.同样,将小于-1的状态代码归一化为零. -1通常表示请求已中止,例如使用config.timeout.请注意,如果响应是重定向,则 XMLHttpRequest 将透明紧随其后,这意味着结果(成功或错误)将取决于最终的响应状态代码.

A response status code between 200 and 299 is considered a success status and will result in the success callback being called. Any response status code outside of that range is considered an error status and will result in the error callback being called. Also, status codes less than -1 are normalized to zero. -1 usually means the request was aborted, e.g. using a config.timeout. Note that if the response is a redirect, XMLHttpRequest will transparently follow it, meaning that the outcome (success or error) will be determined by the final response status code.

> AngularJS $ http服务API参考.

还要注意,状态-1通常是 CORS问题.由于违反了同一来源政策.

Also note that a status of -1 usually is a symptom of a CORS problem. The request being blocked because of a violation of Same Origin Policy.

这篇关于使用.then方法解析时,未定义的$ http数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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