Ember.js 从余烬数据查询访问“links”属性
当使用Ember.js 从余烬数据查询访问“links”属性,ember.js,ember-data,json-api,Ember.js,Ember Data,Json Api,当使用JSONAPIAdaper并查询存储中的模型时,服务器响应包括指定的“links”属性,响应如下 { "links": { "self": "http://localhost:4200/api/v0/blog-posts?size=10", "first": "http://localhost:4200/api/v0/blog-posts?size=10&page=0", "last": "http://localhost:4200/api/v0/blo
JSONAPIAdaper
并查询存储中的模型时,服务器响应包括指定的“links”
属性,响应如下
{
"links": {
"self": "http://localhost:4200/api/v0/blog-posts?size=10",
"first": "http://localhost:4200/api/v0/blog-posts?size=10&page=0",
"last": "http://localhost:4200/api/v0/blog-posts?size=10&page=1",
"next": "http://localhost:4200/api/v0/blog-posts?size=10&page=1"
},
"data": [{
"id": 1,
"type": "blog.posts",
"attributes": {
"published": "2015-04-04T00:56:36.768Z"
},
"relationships": {
"revisions": {
"data": [
{ "id": 1, "type": "blog.post.revisions" },
{ "id": 2, "type": "blog.post.revisions" },
{ "id": 3, "type": "blog.post.revisions" },
{ "id": 4, "type": "blog.post.revisions" }
]
},
"current": {
"data": { "id": 4, "type": "blog.post.revisions" }
}
}
}]
}
注意:我删除了data属性中的大部分元素,并删除了included属性,因为它们使示例变得不必要的大也不要担心类型名,承认它们看起来很奇怪,但我就是这样设置序列化器的(以反映pod结构)
请求它的路由如下所示
import Ember from 'ember';
export default Ember.Route.extend({
model () {
const store = this.get('store');
return store.query('blog.post', { size: 10 });
}
});
我要做的是为我的博客创建一个分页机制,用links属性中指定的链接中的数据替换模型
如何访问此“链接”
属性
版本
ember@2.2
ember data@2.2
链接
对象插入到元
对象中
// pods: app/application/serialiser.js
// vanilla: app/serialisers/application.js
import DS from 'ember-data';
export default DS.JSONAPISerializer.extend({
/**
* will attach links to the meta object
*/
normalizeArrayResponse (...args) {
const normalized = this._super(...args);
//
// since the meta object is optional, it's
// best to verify if it's null/undefined
//
if (normalized.meta == null) {
normalized.meta = {};
}
normalized.meta.links = normalized.links;
return normalized;
}
});
因此,在我的路线中,我可以像这样访问对象的链接
import Ember from 'ember';
export default Ember.Route.extend({
model (params) {
const store = this.get('store');
return store.query('blog.post', params).then(posts => {
//
// access the links object like so.
//
const links = posts.get('meta.links');
return Ember.Object.create({ links, posts })
});
}
});
警告
这不是最好的解决方案,因为它可能会覆盖meta
对象中名为links
的任何属性
克服此问题的一种方法是使用符号作为字段名称,因为符号是唯一的,因此可以确定不会覆盖对象命名空间中的任何现有名称。但我还没有尝试过这个方法,而且它在旧浏览器上可能不会很好地工作,而且我不确定ember的get方法如何与符号交互