Why does an Angular $ resource return a Resource object instead of a class object?

Using CoffeeScript, Angular, and $ resource, I created the following factory:

angular.module('myapp', ['ngResource']).factory 'MyObject', ['$resource', ($resource) ->
    MyObjectResource = $resource '/api/my_object/:id', {
      id: '@id'
    }, {
      update:
        method: 'PUT'
    }

    class MyObject extends MyObjectResource

      someMethod: ->
        dosomething
 ]

The problem is that when I load an object from my API, I get an object Resourceinstead of an object MyObject, which is a problem because I do not have access to my other methods.

Here is my code to get the object:

result = MyObject.get({id: 1})

If I print result, I see:

Resource {id: 1, details: 'somestuff'}

In contrast, I would expect:

MyObject {id: 1, details: 'somestuff'}

which will give me access to someMethodand to all the other methods that I have defined for this class.

Am I doing something wrong?

Thanks in advance.

+4
source share
1 answer

:

  • Resource , factory ( $resource ) $resource.

(, , , , )

function Resource(value) { ... }
Resource.prototype.toJSON = function () { ... }
Resource.prototype.bind = function () { ... }
  1. , $resource 3 ( ), Resource, , update , .

update :

{
  'get': {method: 'GET'},
  'save': {method: 'POST'},
  'query': {method: 'GET', isArray: true},
  'remove': {method: 'DELETE'},
  'delete': {method: 'DELETE'},
  // added by the user
  update: { method: 'PUT' }
}

$resource Resource, Resource, $ , ..

Resource.get = function () { ... }
Resource.save = function () { ... }
Resource.update = function () { ... }
...

Resource.prototype.$get = function () { ... }
Resource.prototype.$save = function () { ... }
Resource.prototype.$update = function () { ... }
...

, , MyObject MyObjectResource, MyObjectResource $resource, Resource, , coffeescript extend , MyObjectResource MyObject, [[Prototype]] MyObject.prototype MyObjectResource.prototype:

MyObjectResource                
  prototype     ------->  MyObjectResource.prototype
                            $get
  get                       $save
  save                      toJSON
  ...                       ...
                             ^
                             |
MyObject                     |
  prototype     ------->  MyObject.prototype
  get (reference)           someMethod
  set (reference)
  ...

, MyObject.get, MyObjectResource.get, MyObject.get === MyObjectResource.get

, MyObject.get, MyObjectResrouce ( , , MyObject.get this MyObjectResource Source), new MyObjectResource(), someMethod, "".

MyObject - , coffeescript extend, get MyObjectResource.prototype.$get, :

var instance = new MyObject()
instance.$get({id: 1});     // works because of the link created between the prototypes
instance.someMethod();      // also works
+5

All Articles