Jeff
Jeff

Reputation: 6953

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.

Upvotes: 0

Views: 73

Answers (2)

code-jaff
code-jaff

Reputation: 9330

Usually these are coming from models. Rendering will be delayed until models are resolved.

Your case can be implemented in a bit different way. Fetch the details on mount/init event and set the resolved value to a property and bind that property with the view. View will be re-rendered once the value is updated

Upvotes: 0

Gokul Kathirvel
Gokul Kathirvel

Reputation: 1610

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

Upvotes: 1

Related Questions