TypeError:Object#<object>在Angular js Http.get request </object>中没有方法'push'

时间:2013-12-23 15:06:21

标签: javascript angularjs laravel-4 eloquent

以下是我的控制器,单击按钮时尝试拉取数据非常简单,并尝试将其推入ng-repeat。

 app.controller('HomeController',function($scope,$http) {

        $scope.user  = [];
        $scope.posts = [];
        $http.get('http://hashtag.dev/api/v1/user').success(function(data) {
            $scope.user = data;
        });
        $http.get('http://hashtag.dev/api/v1/post').success(function(data) {
            $scope.posts = data;
        });

        $scope.loadmore = function() {

            $http.get('http://hashtag.dev/api/v1/post').success(function(data) {
                $scope.posts.push(data);
            });
        };
    });

单击ng-click =“loadmore()”按钮时

 TypeError: Object #<Object> has no method 'push' 

有什么问题?顺便说一句,我是一个完整的角落菜鸟。服务器返回的JSON ..

 {
"total": 37,
"per_page": 10,
"current_page": 2,
"last_page": 4,
"from": 11,
"to": 20,
"data": [
    {
        "id": 84,
        "user_id": 4,
        "post_text": "Sunt eius voluptatem nostrum eos eos ipsa qui. Laudantium ratione repudiandae vitae sunt distinctio earum.",
        "created_at": "2013-12-15 14:29:00",
        "deleted_at": null,
        "user": {
            "id": 4,
            "full_name": "Vinnie Lang",
            "username": "vinnie398",
            "created_at": "2013-12-15 14:28:54"
        }
    },
    {
        "id": 82,
        "user_id": 2,
        "post_text": "Laudantium minus animi alias dolorum aperiam non. Odit quidem doloribus nihil eius incidunt sint nulla.",
        "created_at": "2013-12-15 14:29:00",
        "deleted_at": null,
        "user": {
            "id": 2,
            "full_name": "Shyanne Champlin",
            "username": "shyanne718",
            "created_at": "2013-12-15 14:28:53"
        }
    },...................

3 个答案:

答案 0 :(得分:2)

问题是$scope.posts不是一个数组(或者任何东西,你不能只是push到一个未定义的变量并且期望一个数组来自它。我会在控制器的开头或回调的开头定义一个空数组:

$scope.posts = [];

答案 1 :(得分:1)

假设成功回调到data返回的$http.get('http://hashtag.dev/api/v1/post')是一个对象数组,您必须这样做:

1)在控制器中定义$scope.posts=[],就像定义$scope.user

一样

2)在$http.get('http://hashtag.dev/api/v1/post') loadmore()的成功回调中,您需要使用新数据扩充$scope.posts

$scope.posts = $scope.posts.concat(data);

答案 2 :(得分:0)

试试这个:

修改

$scope.data = { posts : [] }

$scope.loadmore = function() {

    $http.get('http://hashtag.dev/api/v1/post').success(function(data) {
        $scope.data.posts.push.apply($scope.data.posts, data);
    });
};