proper configuration for ngResource

I have 3 objects in my application, Games, Questions, and Answers.

The classes are configured as such:

class Game{
   id;
   Question[] questions;
}

class Question{
    id;
    text;
    Answer[] answers;
}

class Answer{
    id;
    text;
}

I am trying to correctly configure an ngResource to handle this class setup. Ideally, what I'd like to achieve is something like this:

app.factory('gameRepository', function($resource){
    var gameResource = $resource('/api/Games/:id', { id: '@id' });    

    return {
        get: function(id){ return gameResource.get({id: id}); }
    };
});

app.controller('myController', function(gameRepository){
     var game = gameRepository.get(17);
     var questions = game.$getQuestions();
     var answers = questions[0].$getAnswers();
});

I know that some of this can be achieved by doing this:

var gameResource = $resource('/api/Games/:id/:action', { id: '@id', action: '@action' },
    {
        getQuestions: { method: 'GET', isArray: true, params: { action: 'Questions'}
    },

);    

However, I get stuck after this point. Ideally, what I'd like to do is have the $getAnswers method return an object from a different resource (a new questionsResource) and then in turn, have a $getAnswers method that returns from an answers resource. The goal here is to keep the methods on the actual resource object instead of extracting them to a separate factory/service call.

Additionally, I'd like to be able to request a specific question from the repository. Something like this:

var game = gameRepository.get(17);
var question = game.$getQuestion(1);

As far as I can tell, there's no way to pass a specific parameter to a $resource custom action the way I'm using them.

Can anybody point me in the right direction? Thanks!


This ended up being way easier than I thought.

The $resource function creates a function that all objects returned from the resource inherit. As a result you can do something like this:

gameResource.prototype.$getQuestion = function(id){ ... }
链接地址: http://www.djcxy.com/p/89556.html

上一篇: 角度$资源不按预期工作

下一篇: ngResource的正确配置