문제

I have two factories as follows:

angular.module('categoryResource', ['ngResource', 'userResource'])
.factory('categories', function ($http, users){
    var factory = {};
    factory.getCategories = function () {
        return $http.get('/api/userCategories');
    };
    factory.getCategoriesUsers = function () {
        //call factory.getCategories(), parse the request to make it nice and tidy
        //then call users.getUsers(), tidy them up in the same way as categories, join them together and return them all in a nice package.
    };

    var handleCategoriesUsers = function (data, status) {

    }

    return factory;
});

angular.module('userResource', ['ngResource'])
.factory('users', function ($http) {
    var factory = {};
    factory.getUsers = function () {
        return $http.get('/api/users');
    };
    return factory;
});

I've already made a nice treeView with the Categories but I want to also add Users to those categories; so to this end I thought I'd just format the users into something my treeView algorithm can already work with.

My question is, Can I somehow do It within the categories factory (or even a different module/factory altogether) and just return the joined results at the same time? If yes, how? Do I need to define a handler for $http.get like I usual? then in that handler, call the other get then define a handler for that and then return the result?

도움이 되었습니까?

해결책

I'm not 100% sure I understand the question, but have you looked at $q.all? It seems like you want to compose/combine multiple promises into a single, easy to handle package. I'd give you a description and some code samples, but egghead did it better: https://egghead.io/lessons/angularjs-q-all

Is this what you're looking for?

EDIT: In case just dumping a link is frowned upon:

var all = $q.all([one.promise, two.promise, three.promise]);
    all.then(success)

    function success(data) {
        console.log(data);
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top