2014-02-06 19 views
0

我有兩個工廠如下:我可以使用另一工廠內的工廠來一起加入兩個REST請求嗎?

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定義處理程序?那麼在那個處理程序中,調用另一個然後定義一個處理程序,然後返回結果?

回答

1

我不是100%確定我明白這個問題,但是你看過$ q.all嗎?看起來你想要將多個承諾組合成一個易於處理的包。我會給你一個描述和一些代碼示例,但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); 
    } 
+0

這是真正有用的,但我得看看我可以用它解決我的問題:如果只是傾銷的鏈接是不可取的。即使它在我目前希望它工作的形式中沒有用處,它將對計劃B有很大的幫助(只需將它們兩個並在控制器中解析以獲得我想要的格式)。謝謝 – Bogdan

+0

好吧,你不一定非要在控制器中做到這一點。你可以在你的服務中注入$ q,創建/返回一個新的promise,然後通過$ q.all – UnicodeSnowman

+0

來解析這兩個requiests,如下所示:http://embed.plnkr.co/irmiddNu2nmucFGOuuux/app.js – UnicodeSnowman

相關問題