How to finalize a loading screen after executing promisses in the Angular?

0

Good morning.

I have a question, I have a controller that searches for some data from a webservice rest, and persists them in the database of the device (ionic), to search the data, I'm using 'promises'.  

When you start the search I open a Loading screen, and I would like you to finish all promises, close the loading screen.

  

I'm doing the following:

LoadingService.show();

var promise = function1.promise();
promise.then(function (result) {
    if (result) {
        MeuService.insert(result);
    }
});

var promise2 = function2.promise();
promise2.then(function (result) {
    if (result) {
        MeuService.insert(result);
    }
});

var promise3 = function3.promise();
promise3.then(function (result) {
    if (result) {
        MeuService.insert(result);
     // Já tentei deixar aqui tbm..
    // LoadingService.hide();
    }
});

//??
LoadingService.hide();

The problem is that soon after starting, it already closes the loading, and continues execution of promisses.  Where am I going wrong?

    
asked by anonymous 07.06.2016 / 16:25

1 answer

0

You can use the all method of $ q, which is the service that provides promises in angle 1.

As follows:

LoadingService.show();

function insertResult(result) {
  MyService.insert(result);
}

var promise1 = function1.promise();
var promise2 = function2.promise();
var promise3 = function3.promise();

$q.all([
  promise1.then(insertResult),
  promise2.then(insertResult),
  promise3.then(insertResult)
]).then(function() {
  LoadingService.hide();
});

In this way the LoadingService.hide will only be executed after all promises have been resolved.

    
07.06.2016 / 22:28