I'm trying to build a backend Angular data model in my Rails/Angular app. I have a Base class, from which all other models inherit. This is what it looks like, truncated, in Coffeescript:
mod = angular.module("Models")
mod.factory "Base", ($resource) ->
class Base
constructor: (properties) -> _.extend(this, properties)
@generateFromJSON: (factory, json) ->
return null unless json?
if _(json).isArray()
objs = []
for elem in json
objs.push(new factory(elem))
return objs
else
return new factory(json)
@resource: (path, passedOptions) ->
options = _.merge({ method: 'GET', params: {} }, passedOptions)
$resource path, {}, options
return Base
The idea is that I can use this resource method as a shorthand for creating model-specific RESTful query methods that are based off of ngResource but soup things up, a) by renaming the query methods, and b) by wrapping the return values of the query as instances of the model (using my generateFromJSON method).
So my Item model looks like this:
mod = angular.module("Models")
mod.factory "Item", ($resource, Base) ->
class Item extends Base
@fromJSON: (json) -> Base.generateFromJSON(Item, json)
@resource: (passedOptions) ->
Base.resource('/api/v1/items/:itemId', passedOptions)
@all: ->
response = @resource({isArray: true}).query()
@fromJSON(response)
@find: (id) ->
response = @resource( params: {itemId: id} ).query()
@fromJSON(response)
@where: (conditions) -> _.where(@all(), conditions)
return Item
Basically, these querying methods (like all) use the Item resource method, which in turn uses the Base resource method, which in turn uses ngResource, to query my endpoint.
This works. If I then console log the return value of Item.all(), I get all the items.
What's weird is that running @fromJSON on the response yields an empty array. And if I try to debug it by throwing a debugger in between the response = line and the @fromJSON line in all, response is an empty array, even though _I had just seen that the value of @resource({isArray: true}).query() was all my items`.
I'm super confused. I'm guessing this is some sort of JS timing/promise thing, but I don't get why it'd only work when I don't try to do anything with the response.
Thoughts? Am I missing something obvious?
Aucun commentaire:
Enregistrer un commentaire