Angular Resource: Error: $resource:badcfg

Angular Resource: Error: $resource:badcfg

我已经查看了这里的其他帖子,但仍然无法解决我的问题。

我得到一个错误:

$resource:badcfg Response does not match configured parameter

我认为这个错误是由于return使用数组而不是对象引起的,反之亦然。

这是我的代码:

在我的工厂里(我添加了 isArray: false 但还是不走运)

var task = $resource('http://localhost:5000/task/:id', {id:'@id'}, {
    'get': {method:'GET', isArray: false},
}); 

然后在我工厂的return部分

    find: function(id){
      return task.get({ id: id });
    }

在我的 Flask 服务器中,当我加载页面时它会做出正确的响应:

127.0.0.1 - - [28/Feb/2017 14:35:13] "GET /task/1 HTTP/1.1" 200 -

但是我仍然收到错误消息?

如果我把它放在浏览器中,这也是我的服务器提供的 http://localhost:5000/task/1

[{"completed": true, "id": 1, "ownerName": "Ryan", "task": "Test Activity", "title": "A test task"}]

我也试过这个并得到同样的错误:

console.log(task.get({ id: 1 }));

您是否尝试过类似的东西:

var task = $resource('http://localhost:5000/task/:id', {id:'@id'}, {
    'get': {method:'GET', isArray: false},
  });

您错过了 {id:'@id'} 传递参数 id

原来我需要将 isArray: false 设置为 true 所以:

  var task = $resource('http://localhost:5000/task/:id', {id:'@id'}, {
    'get': {method:'GET', isArray: true},
  });

This error occurs when the $resource service expects a response that can be deserialized as an array but receives an object, or vice versa. By default, all resource actions expect objects, except query which expects arrays.

To resolve this error, make sure your $resource configuration matches the actual format of the data returned from the server.

--AngularJS Error Reference - $resource:badcfg

$resource 的默认操作是:

{ 'get':    {method:'GET'},
  'save':   {method:'POST'},
  'query':  {method:'GET', isArray:true},
  'remove': {method:'DELETE'},
  'delete': {method:'DELETE'} };

避免更改默认方法:

var task = $resource('http://localhost:5000/task/:id', {id:'@id'}, {
    //AVOID changing default
    //'get': {method:'GET', isArray: true},
});

改为使用 query 操作方法:

find: function(id){
  //return task.get({ id: id });
  //INSTEAD use query action method
  return task.query({ id: id });
}

这将避免混淆熟悉 $resource 服务约定的程序员。

有关详细信息,请参阅 AngularJS $resource API Reference


使用transformResponse从数组中提取对象

如果服务器错误地返回包含在数组中的资源对象,可以使用响应转换函数提取:

var task = $resource('http://localhost:5000/task/:id', {id:'@id'}, {
    'get': {method:'GET',
            transformResponse: function(json) {
                var data = angular.fromJson(json);
                if ((typeof data == 'array' && (data.length == 1)) {
                   return data[0];
                } else {
                   return data;
                };
            } 
     }
});