预期的数组但收到...(JSON)...... AngularJS错误

时间:2016-12-24 17:26:30

标签: javascript angularjs arrays json node.js

我正在从Adam Freeman的Pro AngularJS“书中学习Angular1。我在构建他在第6-8章中描述的DeployD应用程序时遇到了问题 - 似乎我的代码不想读取JSON < / p>

这是我的HTML:

<!DOCTYPE html>
<html ng-app="sportsStore" lang="pl">
<head>
    <title>SportsStore</title>
    <script src="components/angular.js"></script>
    <script src="components/angular-resource.js"></script>
    <link href="components/bootstrap.css" rel="stylesheet" />
    <link href="components/bootstrap-theme.css" rel="stylesheet" />
    <script>
        angular.module("sportsStore", ["customFilters"]);
    </script>
    <script src="controllers/sportsStore.js"></script>
    <script src="filters/customFilters.js"></script>
    <script src="controllers/productListControllers.js"></script>
</head>
<body ng-controller="sportsStoreCtrl">
<div class="navbar navbar-inverse">
    <a class="navbar-brand" href="#">SKLEP SPORTOWY</a>
</div>
<div class="panel panel-default row" ng-controller="productListCtrl">
    <div class="alert alert-danger" ng-show="data.error">
        Błąd ({{data.error.status}}). Dane produktu nie zostały wczytane.
        <a href="/index.html" class="alert-link">Kliknij tutaj, aby spróbować ponownie</a>
    </div>
    <div class="panel panel-default row" ng-controller="productListCtrl"
         ng-hide="data.error">
    <div class="col-xs-3">
        <a ng-click="selectCategory()"
           class="btn btn-block btn-default btn-lg">Strona główna</a>
        <a ng-repeat="item in data.products | orderBy:'category' |
unique:'category'" ng-click="selectCategory(item)" class=" btn btn-block
btn-default btn-lg" ng-class="getCategoryClass(item)">
            {{item}}
        </a>
    </div>
    <div class="col-xs-8">
        <div class="well"
             ng-repeat="item in data.products | filter:categoryFilterFn |
range:selectedPage:pageSize">
            <h3>
                <strong>{{item.name}}</strong>
                <span class="pull-right label label-primary">
{{item.price | currency}}
</span>
            </h3>
            <span class="lead">{{item.description}}</span>
        </div>
        <div class="pull-right btn-group">
            <a ng-repeat="page in data.products | filter:categoryFilterFn |
                    pageCount:pageSize" ng-click="selectPage($index + 1)" class="btn
btn-default" ng-class="getPageClass($index + 1)">
                {{$index + 1}}
            </a>
        </div>
    </div>
</div>
</body>
</html>

和sportStore.js控制器

angular.module("sportsStore")
    .constant("dataUrl", "http://localhost:5500/products")
    .controller("sportsStoreCtrl", function ($scope, $http, dataUrl) {
        $scope.data = {};
        $http.get(dataUrl)
            .then(function (data) {
                $scope.data.products = data;
            },
            function (error) {
                $scope.data.error = error;
            });
    });

我正在使用DeployD来构建API,问题是当我尝试运行我的应用程序时,错误会显示在控制台中:

  

错误:[filter:notarray]预期的数组但收到了:   {“data”:[{“name”:“Kajak”,“description”:“Łódkaprzeznaczonadla jednej   osoby “ ”类别“:” 动感   Wodne “ ”价格“:275, ”ID“: ”d9b9e4fcb9df3853“},{ ”名“:” Kamizelka   ratunkowa“,”description“:”Chroni i dodaje uroku“,”category“:”Sporty   wodne “ ”价格“:49.75, ”ID“: ”3c1cceedb44ddb84“},{ ”名“: ”Piłka“, ”说明“:” Zatwierdzona   przez FIFA rozmiar i waga“,”类别“:”Piłka   Nożna “ ”价格“:19.5, ”ID“: ”447a2079a8488932“},{ ”名“:” FLAGI   narożne“,”描述“:”NadadząTwojemuboisku profesjonalny   wygląd “ ”类别“:” Piłka   Nożna “ ”价格“:34.95, ”ID“: ”2b2dd597f18bb8a7“},{ ”名“: ”体育场“, ”说明“:” Składany   stadion na35000osób“,”类别“:”Piłka   Nożna “ ”价“:79500, ”ID“: ”2cfe0f6767240bf9“},{ ”名“: ”Czapka“, ”说明“:” Zwiększa   efektywnośćmózguo   75% “ ”类别“: ”Szachy“, ”价格“:16, ”ID“: ”dfc137db43574b4a“},{ ”名“:” Niestabilne   krzesło“,”描述“:”Zmniejszaszansę   przeciwnika “ ”类别“: ”Szachy“, ”价格“:29, ”ID“: ”e2b644c5091d28ca“},{ ”名“:” Ludzka   szachownica“,”“description”:“Przyjemna gradlacałej   rodziny “ ”类别“: ”Szachy“, ”价格“:75, ”ID“: ”f945806bb011895d“},{ ”名“:” Błyszczący   król“,”“description”:“Pokrytyzłotemiwysadzany diamentami   KROL”, “类别”: “Szachy”, “价格”:1200, “ID”: “fab242704bb38b64”}], “状态”:200, “配置”:{ “方法”: “GET”, “transformRequest”: [空], “transformResponse”:[空], “jsonpCallbackParam”: “回调”, “URL”: “http://localhost:5500/products”, “标题”:{ “接受”:“应用/ JSON,   text / plain, / “}},”statusText“:”OK“}   http://errors.angularjs.org/1.6.0-rc.1/filter/notarray?p0=%7B%22data%22%3A% ...的儿子%2C%20text%2Fplain%2C 20%*%* 2F%22%7D%7D%2C%22statusText%22%3A%22OK%22%7D       在angular.js:68       在angular.js:20392       at fn(eval at compile(angular.js:15095),:4:388)       在regularInterceptedExpression(angular.js:16203)       在Scope。$ digest(angular.js:17732)       在Scope。$ apply(angular.js:18006)       完成后(angular.js:12150)       at completeRequest(angular.js:12376)       在XMLHttpRequest.requestLoaded(angular.js:12304)

我试图在SO上略过类似的错误,但没有一个解决方案似乎适合我。有人有类似的问题吗?

4 个答案:

答案 0 :(得分:1)

ng repeat适用于数组但是根据then()方法中的API获取的响应不是数据本身,而是具有名为data的属性,这是实际的您必须传递的数组ng-repeat

因此,不要使用$scope.data.products = data使用$scope.data.products = data.data

----------OR----------

.then(function (response) {
  $scope.data.products = response.data;
}

答案 1 :(得分:1)

错误消息显示过滤器拒绝处理响应对象而不是数据数组。 Expected array but received: {data:[..., headers: ...

.then服务的$http方法返回响应对象,而不是数据。

angular.module("sportsStore")
    .constant("dataUrl", "http://localhost:5500/products")
    .controller("sportsStoreCtrl", function ($scope, $http, dataUrl) {
        $scope.data = {};
        $http.get(dataUrl)
            //.then(function (data) {
            //    $scope.data.products = data;
            .then(function (response) {
                $scope.data.products = response.data;
            },
            function (error) {
                $scope.data.error = error;
            });
    });

数据只是响应对象的一个​​属性:

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

答案 2 :(得分:0)

ng repeat和filter适用于数组,您需要访问数据

 angular.module("sportsStore")
    .constant("dataUrl", "http://localhost:5500/products")
    .controller("sportsStoreCtrl", function ($scope, $http, dataUrl) {
        $scope.data = {};
        $http.get(dataUrl)
            .then(function (data) {
                $scope.data.products = data.data;
            },
            function (error) {
                $scope.data.error = error;
            });
    });

答案 3 :(得分:0)

Angular期望数据变量是数组的类型。

$scope.data =  [];

然后尝试以下代码:

$http.get('dataUrl')
    .success(function(data) {
        $scope.data = data;
    }).error(function(data, status) {
        $log.error('Error ' + status + ' unable to get data from server.');
});

还要记得在控制器中添加$log以正确显示控制台中的错误:

.controller('sportsStoreCtrl', ['$scope', '$http', '$log', function ($scope, $http, $log)