EmberJS没有请求从rest api获取数据

EmberJS not making a request to get data from rest api

本文关键字:api 获取 数据 rest 请求 EmberJS      更新时间:2023-09-26

我正在尝试将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"
         }
       ]
   }
}

好的,这里有一些事情。首先,没有路由定义,也就是指定成员应该如何查找模型数据的地方。在这种情况下,您可以使用调用您的api的模型挂钩指定应用程序路由,例如:

App.ApplicationRoute = Ember.Route.extend({
  model: function(){
    return App.Response.find();
  }
});

有了这个,ember将尝试调用你的api。但是请求不会指向您期望的url:相反,它将调用/myapp/stuff/list/responses,因为ember将复数模型名称附加到适配器的基本url。

最后,如果你的api返回上面的json,ember会抱怨你的服务器返回了一个带有密钥响应的散列,但你没有它的映射。按照惯例,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,输出

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);
    });
  }
});