使用ActiveModelAdapter在ember

时间:2015-09-30 17:11:35

标签: json ember.js ember-data

我在我的Ember应用程序中使用标准的ActiveModelAdapter来完成大部分查询以使用Ember模型对象。

但是,在一种情况下,我想制作一个任意的REST请求来获取JSON来填充图表(不是由模型支持),但我想“通过”ActiveModelAdapter以便使用正确的主机值。

这是什么不起作用:

updateChartFromIndustry: function() {
  Ember.$.ajax({
    context: this,
    method: 'get',
    url: 'api/v3/charts/all_risk.json',
    dataType: 'json',
    data: { ind: this.get('ind') }
  }).then(function(json) {
      Ember.$('#risk-days-data').highcharts(json);
    },
    function(errs) {
      console.log(errs);
    }
  );
}.observes('ind'),

在开发中,该查询转到localhost:4200(ember服务器)而不是localhost:3000的rails后端。显式设置完整URL会使查询通过但没有用于验证请求的各种用户会话信息。

我真的希望有一些简单的东西:

this.store.query('arbitrary url and params', ....)

好像我正在为模型进行正常查询,或者,也可以利用适配器:

Ember.adapter.$.ajax(....) 

2 个答案:

答案 0 :(得分:2)

我发布这个" a"这样做的方式,不一定是正确的方法。

简短的回答是适配器通过this.container.lookup('adapter:application')可用(即使在组件中)。它可以用于直接发送AJAX查询。我认为你可以设置自己的适配器并覆盖默认行为,但在这种情况下,我能够以我想要的方式使用默认适配器来欺骗它。

updateChartFromIndustry: function() {
  let adapter = this.container.lookup('adapter:application');

  // create the URL. Not that the 'chart' is, by default, pluralized to "charts".
  // This happened to be good for my API.
  // The second parameter becomes the "id" which I use to identify
  // the chart name. 
  // http://localhost:3000/api/v3/charts/all_risk
  let url = adapter.buildURL('chart', 'all_risk'); 

  // object.data is automatically converted into query params
  let params = { data: { ind: this.get('ind') } };

  // make the GET request and build the Chart with the response
  adapter.ajax(url, 'GET', params).then(function(response) {
    Ember.$('#my-chart').highcharts(response);
  });
}.observes('ind'),

P.S。这是使用ActiveModelAdapter完成的,但是从DS.RESTAdapter派生的任何内容都应该允许相同的行为。

答案 1 :(得分:0)

启动服务器时可能需要添加代理标志:

ember server Starts the server. The default port is 4200. Use the --proxy flag to proxy all ajax requests to the given address. For example, ember server --proxy http://127.0.0.1:8080 will proxy all ajax requests to the server running at http://127.0.0.1:8080.

来自http://www.ember-cli.com/user-guide/#using-ember-cli