Undefined $http data when resolved with `.then` method

隐身守侯 提交于 2019-12-08 07:31:29

问题


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>

回答1:


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.




回答2:


Rewrite the getMoreData function by using a callback. See the code sample below

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

In essence since you do not know exactly when the getMoreData function will return a value from the http get method you pass the returned data of the http get into a callback function. You then utilize the data from the http get by implementing the callback method in your maincontroller like below:

app.controller('MainController', ['$scope', 'blogpostservice',
    function ($scope, blogpostservice) {
        $scope.pagec = 1;
        this.getMoreData = function () {
            blogpostservice.getMoreData($scope.pagec,function(data){ $scope.posts = data; console.log($scope.posts); })
        }

        this.getMoreData();

    }]);

You also need to ensure you that an array is returned from $scope.posts.

Note that in your html you are interpolating {{post}} instead of {{posts}}



来源:https://stackoverflow.com/questions/45766361/undefined-http-data-when-resolved-with-then-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!