Ember.js v2在路径中加载多个模型而不进行单独的请求

时间:2017-01-10 14:04:52

标签: ember.js routes ember-data models

刚刚开始使用Ember.js,所以在我自己完成了几周的各种教程(...)之后,我真的无法解决以下问题。

我想在1条路线上显示4个模型。我怎么能这样做,同时避免进行4次服务器调用?

更多信息:

我想在我的索引页面上显示“人物”,“引用”,“产品”和“案例”类型的记录。

在我的索引路线中,( routes / index.js )我可以使用以下方式加载它们:

import Ember from "ember";

export default Ember.Route.extend({
  model(){
    return Ember.RSVP.hash({
      persons : this.get('store').findAll('person'),
      quotes  : this.get('store').findAll('quote'),
      cases   : this.get('store').findAll('case'),
      products: this.get('store').findAll('product')
    });
  }
});

(在我的适配器中,adapter / application.js,我有:)

import DS from "ember-data";

export default DS.JSONAPIAdapter.extend({
  host       : 'http://localhost:8080/dummy.php',
  pathForType: function (type) {
    return "?type=" + type;
  }
});

这非常好用:),但是ember.js提出了4个请求:

enter image description here

但是,我可以轻松提供一个JSON文件,提供所有4种类型的记录。

那么,我怎么能告诉ember.js:

  

“这是一个很好的大型JSON文件,里面有很多记录。现在,只使用记录   人物模型的“人”类型,以及“案例”的同意,   'quote'和'product'

2 个答案:

答案 0 :(得分:1)

每个请求加载模型没有错。如果模型是相关的,那么您应该考虑在它们之间定义relationship。再次加载任何异步数据,它将发出网络请求。

如果你想在不同型号的单一请求中加载数据,那么你可以尝试下面的,这不是ember-data方式。所以我不会鼓励这一点。

import Ember from "ember";

const {RSVP} = Ember;

export default Ember.Route.extend({
  model() {
    return RSVP
      .resolve(Ember.$.getJSON('http://localhost:8080/dummy.php'))
      .then((result) => {
        this.get('store').pushPayload(result);
        return {
          persons : this.get('store').peekAll('person'),
          quotes  : this.get('store').peekAll('quote'),
          cases   : this.get('store').peekAll('case'),
          products: this.get('store').peekAll('product')
        };
      });
  }
});

答案 1 :(得分:-1)

好吧,您可能可以在适配器中实现此功能。这可以让你知道你可以做什么:

export default DS.JSONAPIAdapter.extend({
  init() {
    this._super(...arguments);
    this.set('toLoad', {});
  },

  loadDebounces() {
    const toLoad = this.get('toLoad');
    this.set('toLoad', {});
    const keys = Object.keys(toLoad);

    const data = magicLoadForAllAllKeys(); // just do something you like here. Sent the keys as POST, or GET array, websockets, smoke signals..
    Object.keys(data).forEach(key => {
      toLoad[key].resolve(data[key]);
    });
  },

  findAll (store, type, sinceToken, snapshotRecordArray)  {
    return new Ember.RSVP.Promise((resolve, reject) => {
      this.set(`toLoad.${type}`, { resolve, reject });
      Ember.run.debounce(this, this.loadDebounces, 1);
    });
  },
});

你基本上可以去掉多个请求并将它们作为一个处理。但是,这不是RESTFull,也不是JSONAPI。提一下这个。