2015-07-16 2 views
7

Я возвращающая массив объектов с сервера:

[{id: 1, name: "name"},{id: 2, name: "name2"}] 

Теперь я использую угловой-ресурс $query для выборки данных, как он ожидает массив. Когда данные получены, я получаю эту ошибку:

TypeError: value.push is not a function 

Есть ли проблема с ответом я даю от сервера =?

Источник ошибки:

// 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; 
       } 
       } 

Контроллер:

var stream = []; 
stream = new VideoStream({param: 'streamTypes'}); 
stream.$query(); 

Услуги:

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

     }); 
    } 
]); 

enter image description here enter image description here enter image description here

VideoStream:

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

     }); 
    } 
]); 
+0

Давайте [продолжить это обсуждение в чате] (http://chat.stackoverflow.com/rooms/ 83452/дискуссионной между-Гранди-и-Каспар). – Grundy

ответ

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(); 

От https://docs.angularjs.org/api/ngResource/service/$resource:

$ возвращает ресурс:

A resource "class" object with methods for the default set of resource actions optionally extended with custom actions. The default set contains these actions:

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

Calling these methods invoke an $http with the specified http method, destination and parameters. When the data is returned from the server then the object is an instance of the resource class. The actions save, remove and delete are available on it as methods with the $ prefix

+0

Это вызвано тем, что я использую .service вместо .factory? – Kaspar

+1

@ Kaspar, nope, похоже, потому что экземпляр может отображаться только на один объект. – Grundy

+2

Способ работы $ resource заключается в том, что при определении ресурса $ он возвращает класс с помощью некоторых методов класса, таких как запрос и получение. Вызов этих методов создаст новый экземпляр вашего класса.Вам не нужно «новый» ваш класс, если у вас нет существующих данных, которые вы хотите преобразовать в класс ресурсов. Дополнительная информация на https://docs.angularjs.org/api/ngResource/service/$resource – Wawy

1

Дополнительно ответить Wawy «s, согласно документации here:

The action methods on the class object or instance object can be invoked with the following parameters:

  • HTTP GET "class" actions: Resource.action([parameters], [success], error])
  • non-GET "class" actions: Resource.action([parameters], postData, [success], [error])
  • non-GET instance actions: instance.$action([parameters], [success], [error])

О проверке значение VideoStream в контроллере, мы находим:

function Resource(value) { 
     shallowClearAndCopy(value || {}, this); 
    } // Actual Resource class object with regular action(s) we can work with 

там

Вызов VideoStream({param: 'streamTypes'}) возвращается:

undefined // Cannot call anything of undefined 

и new VideoStream({param:'streamTypes'}) возвращается:

Resource {param: "streamTypes"} 
// Instance of the Resource class (an object) where $action(s) are available 
// Verified in the chrome console 

Имея это в виду, дело должно быть:

var stream = []; 
stream = VideoStream.query({param: 'streamTypes'}); 
Смежные вопросы