0

I'm using $rootScope.$emit to call a function inside another controller.

// Call
$rootScope.$emit('validarDadosBasicos');

// Declaration
$rootScope.$on('validarDadosBasicos', function(event) {            
    consistirDadosBasicos().then(result => {
         vm.factory.abasValidas.dadosBasicos = result;
    });
});

consistirDadosBasicos is a async function that return a promise.

After execute "validarDadosBasicos" I need to execute a lot of validations, but I need to wait this function return.

I'ts possible to return a promise inside $on? Are there a some way to force $emit to wait this return.

  • Why not just emit the event when ready? – Sterling Archer Dec 07 '17 at 20:00
  • How can I do it? the validarDadosBasicos function is used in 3 controllers. In this case, after emit the event, I need to get the return to set the path I must follow. – Carlos Henrique Biazin Esteves Dec 07 '17 at 20:32
  • This doesn't work how you think it does. The events are async you don't call them and get a response you just trigger the event and handlers handle the event. Instead of using an event use a provider (service or factory) as a bridge between the controllers you can register callback functions on the service/factory and store them in an array then fire them off when the data you need is ready. This is one of many problems with relying on events for passing around data in angular. With redux type pattern of reducers and events, events can be useful but many times abused in angular. – shaunhusain Dec 07 '17 at 20:32
  • In a service/factory you could also just retain/return the promise/deferred for anything calling the function waiting for the response/resolution of the promise. – shaunhusain Dec 07 '17 at 20:34
  • @shaunhusain, Thanks a lot for your explanation. Do you know where can i find a example of the application of this solution? – Carlos Henrique Biazin Esteves Dec 08 '17 at 08:18
  • @CarlosHenriqueBiazinEsteves https://stackoverflow.com/questions/17667455/angular-http-vs-service-vs-ngresource/17668516#17668516 <-- my answer here has some examples of ways this can be done also see the angular style guide it has a lot of tips on application architecture and do's/do not's. https://github.com/johnpapa/angular-styleguide/tree/master/a1 – shaunhusain Dec 08 '17 at 21:05
  • @CarlosHenriqueBiazinEsteves take my answer there with a grain of salt too that was pretty early in my work with angular still and I'd advocate more now for putting everything into services/factories then injecting those into the controllers and referencing things in the view through the services directly... if you need a more direct example let me know can write up an answer here. – shaunhusain Dec 08 '17 at 21:18

0 Answers0