emberjs 查找然后过滤

emberjs find then filter

在emberjs中,考虑以下数据 (只显示1条记录,正常情况下会有多条记录):

{ "service": [{
    "service-_id":"service_5606ece79bdb05546479739866",
    "service-_rev":"5-62dc477c13ef3ea92869bcdf1a67f1a6",
    "service-company-name":"ABC co.",
    "service-address":"1 2 3 Main Street",
    "service-address-line-2":"",
    "service-city":"asfd",
    "service-state-current":"NY",
    "service-zip":"12345",
    "service-phone":"111",
    "service-fax":"",
    "service-email":"asdf@adsf.com",
    "service-category-current":"web",
    "service-type":"service",
    "id":"service_5606ece79bdb05546479739866"
}]}

如果我想return所有记录,我可以简单地这样做:

App.ServicesRoute = Ember.Route.extend({
    model: function(){
        return this.store.find('service');
    }
});

但是,假设我想 return 当前类别为 'web' 的所有记录。所以在示例数据中,有这个键:service-category-current

我将如何调整我的模型以找到 'service' 然后过滤 service-category-current = 'web' ?

最好的方法是让你的 API 后端处理你发送给它的查询参数(这样你的记录就会在后端被过滤,最好使用查询参数来查询数据库),所以来自服务器的响应将 return 只有与您的查询匹配的记录。示例 store.query 调用:

this.store.query('service', {
  'service-category-current': 'web'
});

这导致从 URL 中获取记录:

http://api.com/services?service-category-current=web

大功告成。但是,如果你不能重构你的后端,你可以在客户端过滤记录:

model() {
  return new Ember.RSVP.Promise(resolve => {
    this.store.findAll('service').then(services => {
      resolve(services.filterBy('service-category-current', 'web'));
    });
  });
}

不是 ES2015 + 使用 Ember.RSVP.Promise 而不是原生 Promise(也许会帮助您解决 Safari 问题):

model: function() {
  var that = this;
  return new Ember.RSVP.Promise(function(resolve) {
    that.store.findAll('service').then(function(services) {
      resolve(services.filterBy('service-category-current', 'web'));
    });
  });
}