【问题标题】:emberjs find then filteremberjs 查找然后过滤
【发布时间】:2025-11-30 17:05:01
【问题描述】:

在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"
}]}

如果我想返回所有记录,我可以这样做:

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

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

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

【问题讨论】:

    标签: ember.js filter find ember-data


    【解决方案1】:

    最好的方法是让您的 API 后端处理您发送给它的查询参数(这样您的记录将在后端过滤,最好使用查询参数来查询数据库),因此来自服务器的响应将只返回与您的查询匹配的记录。示例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'));
        });
      });
    }
    

    【讨论】:

    • 测试了客户端代码,效果很好!感谢您的快速回复!
    • 说得太早了,在 Safari 中,我收到此错误:SyntaxError: Unexpected token '>'(anonymous function)
    • 可能是因为我用过ES2015语法,我会随手更新一下。
    • 我已经更新了答案,使用 Ember.RSVP.Promise 而不是原生 Promise
    • 它有效,但看起来您正在过滤客户端?