mgonto / restangular

AngularJS service to handle Rest API Restful Resources properly and easily
MIT License
7.87k stars 840 forks source link

Nested Restangular "Services" #1254

Open ghost opened 9 years ago

ghost commented 9 years ago

I've been favoring the .service method for exposing model resources in my application.

(function() { 'use strict';

    angular.module('common.resources').
        factory('Article', ArticleFactory).
        factory('Comment', CommentFactory)

    ////////////////////

    function ArticleFactory(Restangular) {
        var resourceUrl = 'articles';

        var Article =  Restangular.service(articles);
        // my current solution - tack on an attribute to the generated service
        Article.resourceUrl = resourceUrl;

        Restangular.extendModel(resourceUrl, function(model) {
            // add some "article" methods here
        });

        return Article;
    }

    ////////////////////

    function CommentFactory(Restangular) {
        var resourceUrl = 'comments';

        var Comment =  Restangular.service(resourceUrl);
        // my current solution - tack on an attribute to the generated service
        Comment.resourceUrl = resourceUrl;

        Restangular.extendModel(resourceUrl, function(model) {
            // add some "comments" methods here
        });

        return Comment;
    }

})();

In my application code, I want to retrieve comments subresources under a particular article resource. I'm currently building the URL via option 1 below. I tack a "resourceUrl" onto the resource, so as to not carry a bunch of magic strings throughout the application.

Is there any other best practice way to use the URL builder to chain services? It's a minor inconvenience, just wondering if anyone has a different approach.

function Controller(Comment, Articles) {
    // hard-coded for simplicity in this example
    var articleId = 1;

    // current solution - option 1
    // GET /articles/1/comments
    Article.one(articleId).all(Comment.resourceUrl).getList();

    // alternative syntaxes (don't work, just curious if there's some other way to accomplish this)
    // Article.one(articleId).all(Comment).getList();
    // Article.one(articleId).all(Comment.getList()).getList();
}
gustavohenke commented 8 years ago

I've been using the following, @giannico:

angular.module( "app" )
    .factory( "users", userFactory );
    .factory( "userPosts", userPostsFactory );

function userFactory ( Restangular ) {
    return Restangular.service( "users" );
}

function userPostsFactory ( Restangular, users ) {
    return function ( userId ) {
        return Restangular.service( "posts", users.one( userId ) );
    };
}

Anyway, a better solution would be awesome.