1

I'm defining a factory using promises like:

.factory('Test', ['$q', '$http', function ($q, $http){
     var getData = function () {
         var deferred = $q.defer();
         $http.get('url')
              .success(function (res) {
                   deferred.resolve(res);
              });

         return deferred.promise;
     }

     return { getData: getData};
}]);

Further in a controller I'm using that factory like:

Test.getData().then(function (data) { console.log(data);});

All works fine, my question is: if I want to use the same promise in another controller to wait for that ajax before I do something else, I should use the same sintax?

Test.getData().then(function (data) { console.log(data);});

My problem is that I'm using a node js socket to retreive some data and events. In my promise I'm connecting the socket

$rootScope.socket = io_connection

and in another controller, on anther page I want to emit an event on that socket but $rootScope.socket gets undefined. Since $rootScope.socket gets defined in that first promise, in my other controller I tried:

$rootScope.socket.emit('custom_event', { id: 1 });

But is undefined... I hope my writing makes sense. Thanks

Iulian Miu
  • 218
  • 2
  • 8
  • maybe you should show the code where you initialize the socket and the controller where you wanna emit an event. You should create the socket in the run phase. - BTW `$http` returns already a promise, there is no need to wrap another layer around it. – Michael Sep 28 '15 at 12:12
  • I made that promise after an example of how to use promises in angular... I will post the code, thanks – Iulian Miu Sep 28 '15 at 12:18
  • ?? Then I'd look for better examples or for examples with a proper explanation. It might be just an example, but in this scenario it doesn't make sense :-) – Michael Sep 28 '15 at 12:21
  • 1
    Avoid the [deferred antipattern](http://stackoverflow.com/q/23803743/1048572)! – Bergi Sep 28 '15 at 12:50
  • [link](https://jsfiddle.net/bxbq8j9z/) here's a part of the code that uses socket – Iulian Miu Sep 28 '15 at 13:02

2 Answers2

1

since your getData always returns a promise, instead of holding the actual data, you can hold the promise object instead:

.factory('LoggedUserData', ['$q', '$http', function ($q, $http) {
    var waitingPromise = null;

    var getData = function () {
        if(!waitingPromise){
            waitingPromise = $http.get('url');
        }
        return waitingPromise;;
    }
    return { getData: getData };
}])

now, irrespective of which controller object gets initaized first, both would recieve the same data.

mido
  • 24,198
  • 15
  • 92
  • 117
0

You need to define witch controller is instantiated first.

I don't know if is a good idea to make controllers dependent on each other if they don't have scope inheritance.

Maybe you can create this socket inside a Service and use on both controllers.

Luiz
  • 542
  • 5
  • 10