我正在尝试将 ember 集成到我的应用程序中。我想用 ember 替换显示记录列表的表。我有一个 rest api,它将返回表的数据。但是,下面的 ember 代码从不请求从 rest api 获取数据。
var App = Ember.Application.create({});
App.Router.map(function() {
});
App.Store = DS.Store.extend({
revision: 11,
adapter: DS.RESTAdapter.extend({
url: '/myapp/stuff/list'
})
});
App.Response = DS.Model.extend({
author: DS.attr("string"),
book: DS.attr("string")
});
以下是我的 html 页面中的内容:
<script type="text/x-handlebars">
<h1>whatever</h1>
{{#each model}}
<h1>{{author}}</h1>
{{/each}}
</script>
但是,在浏览器上我唯一看到的是whatever
。我没有看到 API 的结果,也没有看到对 myapp/stuff/list
发出的请求。
我的 API 如下所示:
{
"meta": {
"code": 200
}
"response": {
"stuff": [{
"id": 1,
"author": "someone",
"book": "some book"
},
{
"id": 2,
"author": "some author",
"book": "anotherbook"
}
]
}
}
最佳答案
好的,这里发生了一些事情。首先是没有路由定义,这是您指定 ember 应如何查找模型数据的地方。在这种情况下,您可以使用调用 api 的模型 Hook 指定应用程序路由,例如:
App.ApplicationRoute = Ember.Route.extend({
model: function(){
return App.Response.find();
}
});
有了这个,ember 将尝试调用您的 api。但是请求不会到达您期望的 url:相反,它会调用 /myapp/stuff/list/responses
,因为 ember 将复数模型名称附加到适配器的基本 url。
最后,如果您的 api 返回上述 json,ember 会提示您的服务器返回了带有 key 响应的散列,但您没有它的映射。按照惯例,API 应该返回一组响应而不是单个响应。以下将起作用:
{
"meta": {
"code": 200
},
"responses": [
{ "id": 1, "author": "someone", "book": "some book "},
{ "id": 2, "author": "some author", "book": "anotherbook" }
]
}
我在这里发布了一个工作示例(使用模拟您的 api 响应的自定义适配器)http://jsbin.com/ICoYUxU/2/edit?html,js,output
App = Ember.Application.create({});
App.Router.map(function() {});
App.Response = DS.Model.extend({
author: DS.attr("string"),
book: DS.attr("string")
});
App.ApplicationRoute = Ember.Route.extend({
model: function(){
return App.Response.find();
}
});
App.Store = DS.Store.extend({
adapter: 'App.Adapter'
});
var responses = {
"meta": {
"code": 200
},
"responses": [
{ "id": 1, "author": "someone", "book": "some book "},
{ "id": 2, "author": "some author", "book": "anotherbook" }
]
};
App.API = {
'/myapp/stuff/list/responses': responses
};
App.Adapter = DS.RESTAdapter.extend({
url: '/myapp/stuff/list',
ajax: function(url, type, hash) {
json = App.API[url];
console.log('App.Adapter.ajax:', url, type, hash, json);
return new Ember.RSVP.Promise(function(resolve, reject) {
Ember.run(null, resolve, json);
});
}
});
关于javascript - EmberJS 没有请求从 rest api 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18347320/