0

我的代码很简单(客户端):

Record.Router.map(function () {
   this.resource('main', { path: '/' });
});


Record.MainRoute = Ember.Route.extend({
    model: function () {
       var response = Record.Rank.find();
       console.log(response.get('name'));
       console.log(response);
       return Record.Rank.find();
    }
});

我的模型:

Record.Rank = DS.Model.extend({
    id: DS.attr('integer'),
    rank: DS.attr('integer'),
    content: DS.attr('string')

});

我使用 RESTadapter:

Record.Store = DS.Store.extend({
   revision: 12,

    adapter: DS.RESTAdapter.reopen({
        namespace: 'recordApp'
    })

});

我的服务器端代码(PHP):

<?php

    namespace RecordContainer;

    echo '{"rank":
                 {
                    "id": "1",
                    "rank": "2",
                     "content": "walla"
                  }
          }';

我希望在我发出之后会有一些东西,Record.Rank.find()但我的console.log(response.get('name'))日志未定义,第二个console.log(response)显示以下内容,没有关于服务器内部回显的信息:

<code>console.log(response)</code> 的输出

如何在 Ember 中查看来自服务器的响应?

4

1 回答 1

2

第一种:调用find不带任何参数的 DS.Model,即Record.Rank.find(),相当于向findAll()您的服务器发送请求。换句话说,它应该获取所有 Record.Rank. 因此 ember-data 需要一个数组以响应格式:

{
  "ranks":[
    {
      "id": "1",
      "rank": "2",
      "content": "walla"
    },
    {
      "id": "2",
      "rank": "5",
      "content": "foo"
    }
  ]
}

第二:即使来自 PHP 的响应是正确的(如上所述),console.log(response.get('name'));也可能会返回,undefined因为请求尚未完成并且记录不可用。如果您真的想访问加载到存储中的记录,您需要将代码放入Promise 解析回调中:

Record.MainRoute = Ember.Route.extend({
    model: function () {
       var response = Record.Rank.find();
       response.then(function(ranks) {
         console.log(ranks.getEach('name'));
       });
       return response;
    }
});
于 2013-07-24T14:39:16.353 回答