简体   繁体   中英

Ember-Data and pulling data into the store

I'm learning Ember and going a bit insane trying to get data from JSON (via REST) into the Ember-Data store.

I've extended an adapter as such:

 App.PostsAdapter = DS.RESTAdapter.extend({
   host: "https://www.foobar.com",
   namespace:"rest",
 }); 

"rest" is a directory on my server already setup to accept certain calls ( /rest/posts sends a JSON string of all posts, /rest/posts/1 sends the post with index 1, etc.)

I have the following to handle the routes in my HTML:

App.Router.map(function() {
  this.resource('about');
  this.resource('posts', function() {
      this.resource('post', { path: ':post_id' });
   });
 });

 App.PostsRoute = Ember.Route.extend({
    model: function() {
    return this.store.find('posts'); 
   }
 });

App.PostRoute = Ember.Route.extend({
 model: function(params) {
 return this.store.findBy('posts', params.post_id);
}
});

This is throwing an error "No model was found for 0" in the Ember console plugin for Chrome, with no specific line of code to work off of. I've tried every permutation of this that I can think of or find online, and nothing's working. Really going insane. When I point to an array in the code, everything works, but I can't for the life of me figure out why the AJAX call is failing.

Example JSON :

 [{
    "id": "27",
    "title": "TITLE A",
    "short_description": "BLAH BLAH",
    "description": " MORE BLAH BLAH BLAH",
    "keywords": "etc etc etc"
},
{
    "id": "26",
    "title": "TITLE B",
    "short_description": "BLAH BLAH",
    "description": " MORE BLAH BLAH BLAH",
    "keywords": "etc etc etc"
}]

I'm sure it's something super obvious that I'm missing, but if anyone can point me in the right direction, I'd be super grateful!!

The returned JSON needs to include the name of the corresponding model.

This is covered in the docs here: http://emberjs.com/guides/models/the-rest-adapter/#toc_json-root

So you need to return:

{
    "posts": [
        {
            "id": "27",
            "title": "TITLE A",
            "short_description": "BLAH BLAH",
            "description": " MORE BLAH BLAH BLAH",
            "keywords": "etc etc etc"
        },
        {
            "id": "26",
            "title": "TITLE B",
            "short_description": "BLAH BLAH",
            "description": " MORE BLAH BLAH BLAH",
            "keywords": "etc etc etc"
        }
    ]
}

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