在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',然后过滤 service-category-current = 'web'?
答案 0 :(得分:3)
最好的方法是让您的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'));
});
});
}
使用Ember.RSVP.Promise
代替原生Promise
而非ES2015 +(可能会帮助您解决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'));
});
});
}