解决资源配置中的错误

时间:2014-05-27 08:00:10

标签: angularjs

我一直在通过以下教程来了解AngularJS: http://jphoward.wordpress.com/2013/01/05/end-to-end-web-app-in-under-an-hourpart-3/

调整了教程后,我得到了以下错误,并且正在努力寻找解决方案。我的理解是它与Factory有关,最初我认为这可能是一个格式错误的API请求,但我似乎在浏览器中得到了正确的结果。

错误:[$ resource:badcfg]资源配置错误。包含一个对象但得到一个数组的预期响应

app.js代码是:

//Main App
var app = angular.module("FixturesApp", ['ngRoute', 'ngResource']).
config(function ($routeProvider) {

    //Routing
    $routeProvider
        .when('/', { templateUrl: 'list.html', controller: ListCtrl })
        .otherwise({ redirectTo: '/' });
});


//Factory
app.factory('Fixture', function ($resource) {
return $resource('/api/fixtures/:id', { id: '@id'}, { update: { method: 'PUT' } });
});

//Directive
app.directive('sorted', [
function() {
    return {
        scope: true,
        restrict: 'A',
        transclude: true,
        template: '<a class="btn btn-link" ng-click="do_sort()" ng-transclude></a>' +
            '<span ng-show="do_show(true)">' +
            '<i class="glyphicon glyphicon-arrow-down"></i>' +
            '</span>' +
            '<span ng-show="do_show(false)">' +
            '<i class="glyphicon glyphicon-arrow-up"></i>' +
            '</span> ',
        controller: function($scope, $element, $attrs) {
            $scope.sort_by = $attrs.sorted;

            $scope.do_sort = function() {
                $scope.sort($scope.sort_by);
            };

            $scope.do_show = function(is_desc) {
                return (is_desc != $scope.is_desc && $scope.sort_order == $scope.sort_by)
            }
        }
    };
}
]);

//Controller
var ListCtrl = function ($scope, $location, Fixture) {
$scope.sort_order = "Id";
$scope.is_desc = false;

$scope.sortString = function (is_desc) {
    return is_desc ? "-" : "";
}

$scope.sort = function (col) {
    if ($scope.sort_order === col) {
        $scope.is_desc = !$scope.is_desc;
    } else {
        $scope.is_desc = false;
        $scope.sort_order = col;
    }
    $scope.search($scope.is_desc);
}

$scope.search = function (is_desc) {
    var fixtureList = Fixture.get({ order: $scope.sortString(is_desc) + $scope.sort_order }, function() {
        $scope.items = fixtureList.results;
    });
}

$scope.search(false);

}

1 个答案:

答案 0 :(得分:0)

看起来您的API返回的字符串不是有效的JSON(JavaScript OBJECT 表示法)。 JSON由键:值对组成。例如:

{"myArray" : 
    [
    {"name" : "John"},
    {"name" : "Sarah"}
    ]
}

你不能直接使用数组=&gt;这不是有效的JSON:

[
    {"name" : "John"},
    {"name" : "Sarah"}
]

简而言之,您的字符串至少应以{而不是[

开头

有关JSON格式的完整说明,请参阅http://json.org/