【问题标题】:Use ActiveModelAdapter to make arbitrary JSON query in ember在 ember 中使用 ActiveModelAdapter 进行任意 JSON 查询
【发布时间】:2015-09-30 17:11:35
【问题描述】:

我在我的 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(....) 

【问题讨论】:

  • 我认为您要么必须使用基本模型来支持图表,要么在 ajax 调用中包含您需要的任何身份验证内容。
  • 回想起来,我认为这是正确的答案。建立图表模型。我可能仍然会这样做,但目前的 hack 如下。

标签: json ember.js ember-data


【解决方案1】:

我将其发布为执行此操作的“一种”方式,不一定是正确的方式。

简短的回答是适配器可通过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'),

附:这是通过 ActiveModelAdapter 完成的,但从 DS.RESTAdapter 派生的任何东西都应该允许相同的行为。

【讨论】:

    【解决方案2】:

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

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-22
      • 1970-01-01
      • 2014-04-13
      • 1970-01-01
      • 1970-01-01
      • 2011-03-16
      • 2018-10-18
      相关资源
      最近更新 更多