切换到RESTAdapter - EmberJS

时间:2015-06-23 13:04:54

标签: ember.js

我一直在看EmberJS教程,但他们都使用FixtureAdapter,我试图切换到RESTAdapter,但我面临持续性错误

Error: Assertion Failed: Expected an object as `data` in a call to push for Books.Book , but was undefined

这里是适配器的代码:

Books.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'http://localhost:24818/api/'});

并在路由器中调用api:

Books.BooksRoute = Ember.Route.extend({
model: function() {
return this.store.find('book',1);
 } 
});

如何让store.find返回要在Handlebars模板中使用的JSON?

非常感谢,

编辑:这是我的API响应:

[{"Id":1,"Title":"Pride and Prejudice","Year":1813,"Price":9.99,"Genre":"Comedy of manners","AuthorId":1,"Author":null},{"Id":2,"Title":"Northanger Abbey","Year":1817,"Price":12.95,"Genre":"Gothic parody","AuthorId":1,"Author":null},{"Id":3,"Title":"David Copperfield","Year":1850,"Price":15.00,"Genre":"Bildungsroman","AuthorId":2,"Author":null},{"Id":4,"Title":"Don Quixote","Year":1617,"Price":8.95,"Genre":"Picaresque","AuthorId":3,"Author":null}]

编辑:添加模型定义:

Books.Book = DS.Model.extend({
title: DS.attr('string'),
year: DS.attr('number'),
price: DS.attr('number'),
genre: DS.attr('string'),
authorId: DS.attr('number'),
author: DS.attr('string')
});

1 个答案:

答案 0 :(得分:1)

我认为您需要规范化您的回复。即

"books": [
    {
       "id":1,
       "Title":"Pride and Prejudice",
       "Year":1813,
       "Price":9.99,
       "Genre":"Comedy of manners",
       "AuthorId":1,"Author":null
    },
    {
       "id":2,
       "Title":"Northanger Abbey",
       "Year":1817,
       "Price":12.95,
       "Genre":"Gothic parody",
       "AuthorId":1,
       "Author":null
    },
    {
       "id":3,
       "Title":"David Copperfield",
       "Year":1850,
       "Price":15.00,
       "Genre":"Bildungsroman",
       "AuthorId":2,
       "Author":null
    },
]

如果您无法控制端点。您需要设置序列化程序或规范化程序,以将响应标准化为此预期格式。

-

有用的链接

Ember-data Model Maker

Ember JSON Conventions

REST Serializer

相关问题