0

I have the following angular service:

app.factory('myFactory', function ($http) {
    var returnedObject = {
        getA: function() { return $http.get('../A'); },
        getB: function() { return $http.get('../B'); },
        getC: function() { return $http.get('../C'); },
    };

    return returnedObject;
});
app.controller('MyService', MyController);

I want to execute a function when all services complete like so:

    $q.all([
        returnedObject.getA().success,
        returnedObject.getB.success,
        returnedObject.getC.success,
    ]).then(function () {
        console.log("promise kept");
    });

I'm just not sure where I can find $q. I'm confused by all the indirection. I'm looking to basically do what was suggested in this question.

Justin Dearing
  • 14,270
  • 22
  • 88
  • 161

2 Answers2

3

just "ask for it" in your function arguments:

app.factory('myFactory', function ($http, $q) {

google "Angular Dependency Injection" for more info

  • 1
    In case you're confused - what's happening here is that angular is finding out what parameter to pass based on the argument name. – Benjamin Gruenbaum Jun 12 '14 at 22:45
  • Wow mind blown! That's so non intuitive. Will try soon. – Justin Dearing Jun 12 '14 at 23:41
  • yeah, it's really an "odd" pattern, and if you're minifying your app it actually breaks and you have to define the arguments separately so that they're not lost. –  Jun 13 '14 at 02:02
-1

Every getFunction should return an promice that $q do.

getA: function() { 
  $http.get('../A').then(function(res){ 
     return res;
  });
 }

And then you can call $q.all()

$q.all([
     getA(),
     getB()
   ]).then(function(data) {
     var a = data[0];
     var b = data[1];
    deferred.resolve(a+b);
  });

Do not forget to inject $q as dependency to your service

paka
  • 1,601
  • 22
  • 35
  • 4
    There is no need to wrap `$http.get` call in such weird way - `$http.get` will return promise itself, and if you need only data from response - you can add `than` right after `get(...)` and return `response.data` from it (`than` from promise will also return a promise) – Bogdan Savluk Jun 12 '14 at 22:32
  • 4
    Adding to what @BogdanSavluk said, this is called the [deferred anti pattern](http://stackoverflow.com/questions/23803743/what-is-the-deferred-anti-pattern-and-how-do-i-avoid-it). – Benjamin Gruenbaum Jun 12 '14 at 22:37
  • 1
    @paka not exactly - `return res.data`, or just remove this `than` call - now it is useless... – Bogdan Savluk Jun 12 '14 at 22:39