TypeError:value.push不是Angularjs $ resource查询的函数

Kas*_*par 7 javascript angularjs angular-resource

我从服务器返回一个对象数组:

[{id: 1, name: "name"},{id: 2, name: "name2"}]
Run Code Online (Sandbox Code Playgroud)

现在我使用angular-resource $query来获取数据,因为它需要一个数组.收到数据后,我收到此错误:

TypeError: value.push is not a function
Run Code Online (Sandbox Code Playgroud)

我从server =给出的响应有问题吗?

错误来源:

 // jshint +W018
                if (action.isArray) {
                  value.length = 0;
                  forEach(data, function(item) {
                    if (typeof item === "object") {
                      value.push(new Resource(item));
                    } else {
                      // Valid JSON values may be string literals, and these should not be converted
                      // into objects. These items will not have access to the Resource prototype
                      // methods, but unfortunately there
                      value.push(item);
                    }
                  });
                } else {
                  shallowClearAndCopy(data, value);
                  value.$promise = promise;
                }
              }
Run Code Online (Sandbox Code Playgroud)

控制器:

var stream = [];
stream = new VideoStream({param: 'streamTypes'});
stream.$query();
Run Code Online (Sandbox Code Playgroud)

服务:

app.service('DataService', [
    '$resource', 'Common', '$rootScope',
    function($resource, Common, $rootScope) {
        return $resource($rootScope.appWebRoot + "myUrl/:param", {param: '@param'},
        {

        });
    }
]);
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述 在此输入图像描述 在此输入图像描述

视频流:

app.service('VideoStream', [
    '$resource', 'Common', '$rootScope',
    function($resource, Common, $rootScope) {
        return $resource($rootScope.appWebRoot + "videoStreams/api/:param",
        {param: '@param'},
        {

        });
    }
]);
Run Code Online (Sandbox Code Playgroud)

Waw*_*awy 9

您遇到的问题是您正在创建资源的实例作为对象

var stream = [];
stream = new VideoStream({param: 'streamTypes'}); //This is the problem. $resource is expecting an array.
stream.$query(); //This is an instance method.

//All you need to do is:
var stream = [];
stream = VideoStream({param: 'streamTypes'}).query();
Run Code Online (Sandbox Code Playgroud)

来自https://docs.angularjs.org/api/ngResource/service/$resource:

$ resource返回:

具有默认资源操作集的方法的资源"类"对象,可选择使用自定义操作进行扩展.默认设置包含以下操作:

{ 'get':    {method:'GET'},
  'save':   {method:'POST'},
  'query':  {method:'GET', isArray:true},
  'remove': {method:'DELETE'},
  'delete': {method:'DELETE'} };
Run Code Online (Sandbox Code Playgroud)

调用这些方法会使用指定的http方法,目标和参数调用$ http.从服务器返回数据时,该对象是资源类的实例.保存,删除和删除操作作为带有$前缀的方法可用

  • $ resource的工作方式是,当你定义一个$ resource时,它会返回一个带有一些类方法的类,比如query和get.调用这些方法将创建一个新类的实例.除非要将现有数据转换为资源类,否则不需要"新"类.更多信息,请访问https://docs.angularjs.org/api/ngResource/service/$resource (2认同)