angularjs - Share data from promise with callback of other controller -
controller sends request via promise. best way of running callback function simultaniously in controller b? either broadcasting via service in original callback , listen in other controller. there possibility in passing promise controller b?
option 1:
// controller service.doajax().then( function( data ) { // controller callback // should broadcast "data" , listen event in controller b ? } ); // controller b $rootscope.$on(); // ... listen event sent controller "data
option 2:
// controller var promise = service.doajax(); shareservice.sharepromise( promise ); // sharing promise broadcast // controller b // promise shareservice via $on() promise.then( function( data) {} );
the problem option 2 callback function executed multiple times. not want share data, execute callback.
you can share promise instead of sharing data. in service:
var cached = null; // assumes ajax doesn't return falsey value function doajax(){ if(!cached) cached = $http.get(...); // actual request return cached; }
that way, when 2 controllers call same request - , triggered whoever calls first. caching promise (and not data) you're preventing class of interesting race conditions.
if don't want cache result, can have special method "who want wait for" implementing sort of barrier or rendezvous pattern:
var awaiters = {}; function randevouz(who){ return new $q(function(resolve, reject){ awaiters[who] = (awaiters[who] || []).concat(resolve); // add new }); } function arrived(who){ (awaiters[who] || []).foreach(function(x){ x(); }); }
which'd let in controller b call:
randevouz("b").then(function(){ // let me know they're ready });
and in a:
doajax().then(function(){ arrived("a"); });
Comments
Post a Comment