7.6 Models -- Finding Records

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

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

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。app

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

2、Retrieving mutiple records异步

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

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

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

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)代替。

3、Querying for multiple recordsui

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

例如,咱们能够查询全部的名字为Peterpserson modelsspa

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

4、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);
  }
})
相关文章
相关标签/搜索