【问题标题】:How can I see my response from server in Ember.js如何在 Ember.js 中查看来自服务器的响应
【发布时间】:2013-07-24 22:45:36
【问题描述】:

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

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) 显示以下内容,没有关于服务器内部回显的信息:

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

【问题讨论】:

  • 在我的脑海中,这是DS.attr('number'),而不是DS.attr('integer')。您不必在模型中定义 id 。另外,我相信商店默认使用DS.RESTAdapter,所以你可以在Store定义之后做reopen

标签: ember.js ember-data


【解决方案1】:

1st:在不带任何参数的 DS.Model 上调用 find,即 Record.Rank.find(),相当于向您的服务器发送 findAll() 请求。换句话说,它应该获取 all 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 resolve callback

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

【讨论】:

  • 另外,如果你进入 chrome dev tools 的 Network 选项卡,然后发起请求,你将能够观察到请求/响应
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-26
  • 2014-04-21
  • 2013-06-23
  • 1970-01-01
相关资源
最近更新 更多