7.6 Models -- Finding Records

Ember Data的store为检索一个类型的records提供一个接口。

一、Retrieving a single record(检索单记录)

1. 通过type和ID使用store.findRecord()去检索一条record。这将返回一个promise,它通过请求的record来实现:

var post = this.store.findRecord('post', 1); // => GET /posts/1

2. 通过type和ID使用store.peekRecord()去检索一条record,没有产生网络请求。只有当它已经在sotre中存在时,这将返回这条record。

var post = this.store.peekRecord('post', 1); // => no network request

二、Retrieving mutiple records

1. 对于一个给定的type,使用store.findAll()来检索所有的records。

var posts = this.store.findAll('post'); // => GET /posts

2. 对于一个给定的type,使用store.peekAll()来检索所有的records,这些records已经被加载到store中,不会产生网络请求:

var posts = this.store.peekAll('post'); // => no network request
  • store.findAll()返回一个DS.PromiseArray,它实现DS.RecordArray并且store.peekAll直接返回一个DS.RecordArray
  • 注意DS.RecordArray不是一个JS数组,这很重要。它是一个实现了Ember.Enumerable的对象。这很重要,因为,例如,如果你想通过index来检索records,[]符号没有用,你必须使用objcetAt(index)代替。

三、Querying for multiple records

Ember Data提供了查询满足某些条件的记录的能力。调用store.query()将获得一个GET请求,并将传递的对象序列化为查询参数。这个方法和find方法一样返回DS.PromiseArray

例如,我们可以查询所有的名字为Peterpserson models

var peters = this.store.query('person', { name: 'Peter' }); // => GET to /persons?name=Peter

四、Integrating with the route's model hook

1. 就像在 Specifying a Route's Model中讨论的一样,routes负责告诉它们的模板加载哪一个model。

2. Ember.Routemodel hook支持开箱即用的异步的值。如果你从model hook中返回一个promise,这个路由器将会等待直到这个promise完成渲染模板。

3. 使用Ember Data使得它很容易使用异步数据编写apps。仅仅从model hook中返回请求的record,并且让Ember处理是否需要网络请求。

app/router.js

var Router = Ember.Router.extend({});

Router.map(function() {
  this.route('posts');
  this.route('post', { path: ':post_id' });
});

export default Router;

app/routes/posts.js

export default Ember.Route.extend({
  model() {
    return this.store.findAll('post');
  }
});

app/routes/post.js

export default Ember.Route.extend({
  model(params) {
    return this.store.findRecord('post', params.post_id);
  }
})
原文地址:https://www.cnblogs.com/sunshineground/p/5165965.html