简体   繁体   中英

Manipulating data from AJAX call in Ember js

I'm new to Ember js and I'm having some difficulty seeing why this isn't working. Essentially i'm sending a GET request to a server and it is giving me an array. I would like to take that array display its contents.

app.js

App.TestRoute = Ember.Route.extend({
    model: function(){
        return App.Test.findAll();
    }
});

App.Test = Ember.Object.extend();

App.Test.reopenClass({

    findAll: function() {
        var dummyArray = [];
        $.ajax({
            type: 'GET',
            url: 'myurl',
            headers: {'myheader'},
            success: function(data){
                data.dummyArray.forEach(function (item){
                    dummyArray.push(App.Test.create(item));
                });
                return dummyArray;
            },
            error: function(request, textStatus, errorThrown){
                alert(errorThrown);
                console.log();
            }
        });
    }
});

When you to the test page the action should fire and an array should be returned to the model where the data can be grabbed to populate the page

and in my HTML I have this:

script type="text/x-handlebars" id="test">
        <ul>
            {{#each item in model}}
                <li>{{item.ID}}</li>
            {{/each}}
        </ul>
        {{outlet}}
    </script>

In the console when I log the data that I returned it looks something like this:

Object {dummyArray: Array[4]}
    dummyArray: Array[4]
        0: Object
            ID: 1111
        1: Object
            ID: 1112
        2: Object
            ID: 1113
        3: Object
            ID: 1114

The app runs with no errors but when I navigate to my test page the page does not populate with any data.

Your problem is that your synchronous code is returning nothing. Your model function returns App.Test.findAll() , which is never anything. You need to return a promise.

findAll: function () {
  var result = [];
  return new Ember.RSVP.Promise(function (resolve, reject) {
    Ember.$.ajax({
      type: 'GET',
      url: 'myurl',
      headers: { 'myheader' },
      success: function (data) {
        data.dummyArray.forEach(function (item) {
          result.push(App.Test.create(item));
        });
        resolve(result);
      },
      error: function (request, textStatus, error) {
        console.log(error);
        reject(error);
      }
    });
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM