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

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

问题描述

我使用了返回从服务器获取的数据数组的控制台日志,但是当我在 html 上调用范围时,我在控制台上收到一个未定义的错误.

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

HTML

 

{{pagec}}

{{posts[1].Title}}

<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="">

解决方案

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

app.service('blogpostservice', ['$http', function ($http) {this.getMoreData = 函数(页数){return $http.get('/api/posts/' + pagecount);}}]);app.controller('MainController', ['$scope', 'blogpostservice',功能($scope,blogpostservice){$scope.pagec = 1;this.getMoreData = 函数 () {blogpostservice.getMoreData($scope.pagec)̶.̶t̶h̶e̶n̶(̶f̶u̶n̶c̶t̶i̶o̶n̶̶(̶d̶a̶t̶a̶)̶̶{̶.then(功能(响应){͟v͟a͟r͟͟d͟a͟t͟a͟͟=͟͟r͟e͟s͟p͟o͟n͟s͟e͟.͟d͟a͟t͟a͟;͟$scope.posts = 数据;console.log($scope.posts);}).catch(函数(响应){console.log("错误:", response.status);抛出响应;});};this.getMoreData();}]);

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

有关详细信息,请参阅 AngularJS $http 服务 API 参考.


更新

<块引用>

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

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

$http(...).then(function onSuccess(response) {//处理成功var data = response.data;var status = response.status;var statusText = response.statusText;var headers = response.headers;var config = response.config;...}).catch(function onError(response) {//处理错误var data = response.data;var status = response.status;var statusText = response.statusText;var headers = response.headers;var config = response.config;...});

来自文档:

<块引用>

响应对象具有以下属性:

  • data – {string|Object} – 使用转换函数转换的响应主体.
  • status – {number} – 响应的 HTTP 状态代码.
  • headers – {function([headerName])} – 头部获取函数.
  • config – {Object} – 用于生成请求的配置对象.
  • statusText – {string} – 响应的 HTTP 状态文本.
  • xhrStatus – {string} – XMLHttpRequest 的状态(completeerrortimeout>中止).

200 到 299 之间的响应状态代码被视为成功状态,将导致调用成功回调.该范围之外的任何响应状态代码都被视为错误状态,并将导致调用错误回调.此外,小于 -1 的状态代码被归一化为零.-1 通常意味着请求被中止,例如使用 config.timeout.请注意,如果响应是重定向,XMLHttpRequest 将透明地跟随它,意味着结果(成功或错误)将由最终响应状态代码决定.

—AngularJS $http 服务 API 参考.

另请注意,状态为 -1 通常是 CORS 问题.由于违反了同源政策.

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>

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();    
    }      
]);

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

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


UPDATE

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?

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;
    ...
  });

From the Docs:

The response object has these properties:

  • 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).

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 Service API Reference.

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天全站免登陆