Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to show or hide spinner according to ajax response in ember.js controller?

I had set an emberjs action for a button so that, whenever a user clicks that button I need to navigate the user to a new page. Before doing transition I need to make several api calls and based on the results of api calls I will transition user to a new page. I have no issues with transitions based on results but I cannot show a spinner image during these api calls.

In the example here I used setTimeout method to delay the transition as I cannot expose the api. In that I could see the console logs are printed in order; but I cant see the spinner during the timeout. Any help will be appreciated regarding this. Thanks in advance.

like image 687
yuva 443 Avatar asked Mar 21 '23 10:03

yuva 443


2 Answers

Use RSVP Promises to wait for all API queries to finish:

App.IndexController = Ember.Controller.extend({
  actions: {
    'goToFoo': function(){
      var Indexcontroller = this;
      showSpinner();

      Ember.RSVP.all(promisesArray).then(function(resultsArray) {
         hideSpinner();
         Indexcontroller.transitionToRoute('foo');
      }, function(error) {
         ...handle errors
      });
    }
  }
});

An ajax request will return a promise, so you can batch them in an array and pass that to the RSVP.all method. The resultsArray will contain the results of every ajax call, in order. The error function will be invoked if any response generates an error.

like image 189
buuda Avatar answered Mar 23 '23 00:03

buuda


In your provided example you call hideSpinner after calling setTimeout which is preceded by a call to your showSpinner function. Since executing those 3 function calls takes a very small amount of time, you couldn't even notice the spinner showing up, because the spinner is hidden again almost instantaneously.

What you need to do is call hideSpinner in your callback function, right after you call transitionToRoute on your controller.

EDIT
Based on @buuda's suggestion and your new example, I've come up with this.

This basically does what @buuda says, create a promise object that will be resolved/rejected based on the AJAX call, and store that object into an array, and pass that array into Ember.RSVP.all().

like image 21
Kemal Fadillah Avatar answered Mar 22 '23 23:03

Kemal Fadillah