javascriptember.jsrsvp-promise

Ajax Promise on Property not returning data


I have an Ember controller with a simple property that should get a list of files from the server. Server-Side all good, data is returning and showing on console.

In controller I have:

imgFiles: new Ember.RSVP.Promise(function(resolve, reject) {
                Ember.$.ajax(ENV.apiHost+'/'+ENV.apiNamespace +'/folderwalk/newsimg', {
                    success: function(response) {
                        // console.log(response);
                        resolve(response);

                    },
                    error: function(reason) {
                        reject(reason);

                    }
                });
            }),

In template:

{{imgFiles}}  // shows [object Object]
{{#each imgFiles as |file|}}   // doesn't loop at all
        x {{file}}
{{/each}}

I've tried all variations I could think of. Encapsulate in function and return the Promise, return response on success,...
Still I can not get the promise to return the actual data.


Solution

  • Yes, when you log the response, you will get the entire payload. But, Ember is unaware of the new data (Previously it would be a Promise) that has been returned from the server. You have to explicitly inform Ember about the new data using set.

      imgList: Ember.computed({
        get() {
          return new Ember.RSVP.Promise((resolve, reject) => {
    
            $.ajax('https://jsonplaceholder.typicode.com/photos').then((data, textStatus, jqXHR) => {
              console.log(data);
              let firstHunPhotos = data.slice(0,100);
              this.set('imgList', firstHunPhotos); // <- set the new data | set the entire data if you want!
            });
          });
        },
        set(key, value) {
            return value // <- don't forget the setter!
        }
      })
    

    Kindly refer to this twiddle. https://ember-twiddle.com/25d11c4c4650c18183df3595ca21f9c3?numColumns=2&openFiles=templates.application.hbs%2Ccontrollers.application.js