【问题标题】:Can I use a factory within another factory to join two REST requests together?我可以使用另一个工厂中的工厂将两个 REST 请求连接在一起吗?
【发布时间】:2014-03-03 16:06:25
【问题描述】:

我有两个工厂如下:

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;
});

我已经用类别制作了一个不错的 treeView,但我还想将用户添加到这些类别中;所以为此我想我只是将用户格式化为我的 treeView 算法已经可以使用的东西。

我的问题是,我可以在类别工厂(甚至完全不同的模块/工厂)内以某种方式执行它并同时返回连接的结果吗?如果是,如何?我需要像往常一样为 $http.get 定义一个处理程序吗?然后在那个处理程序中,调用另一个 get 然后为它定义一个处理程序,然后返回结果?

【问题讨论】:

    标签: angularjs javascript-framework


    【解决方案1】:

    我不是 100% 确定我理解了这个问题,但是你看过 $q.all 吗?似乎您想将多个 Promise 组合/组合成一个易于处理的包。我会给你一个描述和一些代码示例,但 Egghead 做得更好:https://egghead.io/lessons/angularjs-q-all

    这就是你要找的吗?

    编辑:如果只是转储一个链接是不赞成的:

    var all = $q.all([one.promise, two.promise, three.promise]);
        all.then(success)
    
        function success(data) {
            console.log(data);
        }
    

    【讨论】:

    • 这真的很有帮助,但我得看看能不能用它解决我的问题。即使它在我目前希望它工作的形式中没有用,它也会对计划 B 有很大帮助(只需将它们都拿走并在控制器中解析它们以获得我想要的格式)。谢谢
    • 好吧,您不必在控制器中执行此操作。您可以在您的服务中注入 $q,创建/返回一个新的承诺,然后通过 $q.all 解决两个请求
    • 感谢您的示例。我刚开始使用 angular,仍在尝试完全理解 $q,这个例子帮助很大。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多