get xhr return function in ember ajax service

290 views Asked by At

i have an ember service that provide ajax post

import Ember from 'ember';
import ENV from '../config/environment';

export default Ember.Service.extend({
  save(data) {
    return new Ember.RSVP.Promise(
      function (resolve, reject) {
        function progress(e){

          if(e.lengthComputable){
            let max = e.total;
            let current = e.loaded;
            let Percentage = (current * 100)/max;
            console.log(Percentage);
            if(Percentage >= 100)
            {
              // process completed
            }
          }
        }

        Ember.$.ajax({
          type: 'POST',
          enctype: 'multipart/form-data',
          url: ENV.APP.API_HOST + '/profile/lampiran-desas',
          processData: false,
          contentType: false,
          cache: false,
          data: data,
          xhr: function() {
            let myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){
              myXhr.upload.addEventListener('progress',progress, false);
            }
            return myXhr;
          },
          success: function (response) {
            resolve(response);
          },
          error: function (error) {
            reject(error);
          }
        });
      });
  }
});

the success response return normally in my component. But how to get my function progress return. so i can make a loading progress bar on my template..?

thanks..

1

There are 1 answers

0
feanor07 On

As far as I see, you are making a remote call in a service and you desire to display the progress within a component. In order to do that, you need to save the relevant data within the service itself; and display the progress in component.

Here is the twiddle I have prepared for you to illustrate the case. mock-remote-call-service is a mock service that updates process 10% every 200 ms. The result is directly saved to the service itself. progress-displayer-component has the responsibility to display the progress, start the remote call task and even displaying the returned data.

This was just a mock example to explain my point. I hope this helps.