ackuser
ackuser

Reputation: 5889

How to share a model between different controllers through a service in Angular?

I am very new in Angular and I would like to share my problem, just in case someone could help me or guide me to figure it out the best solution.

How do I share retrieved data from a promise (it can be called only once) between different controller through a service or a factory?

I think I should avoid if it is possible emit or broadcasting more on, either timeouts or similar

Anyway, I am sure it has to exist a pattern to do this properly

service('Service', function(...) {

    function ----------(....) {
       return myasyncfunction('..............')
       .then(function(data) {
           return data;
         });
     }

     function getSomething {
       return some operation with DATA;
     }


     return {
     getSomething: getSomething
     }

}

.controller('CtrlA', function (...) {

  Service.getSomething ---> Doesn't work if don't put a delay

}

.controller('CtrlB', function (...) {

}

My code always has dependencies regarding to the fact that I need a promises at the beginning to retrieve the data. I don't know the proper way to create an architecture in which I don't need a watch, timeout or emit/broadcast & on. I suspect it is possible to do in another way

The promise should be called only once

Thx in advance

Upvotes: 0

Views: 25

Answers (1)

Nagender Rawat
Nagender Rawat

Reputation: 141

I should also have to use .then on promise(inside your controller) returned by service like -:

   Service.getSomething.then(function(result){
     //your promise resolve code
   },function(error){
    //your promise reject code
   })

Upvotes: 0

Related Questions