【问题标题】:Accessing the `links` property from a ember data query从 ember 数据查询访问 `links` 属性
【发布时间】:2016-02-25 06:04:18
【问题描述】:

当使用JSONAPIAdaper,并在商店中查询模型时,服务器响应包含json-api spec 指定的"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 属性中的大部分元素并删除了包含的属性,因为它们使示例变得不必要地大。 另外不用担心类型名称,诚然它们看起来很奇怪,但这就是我设置序列化器的方式(以反映 pod 结构)。

请求它的路由看起来像这样

import Ember from 'ember';


export default Ember.Route.extend({
  model () {
    const store = this.get('store');
    return store.query('blog.post', { size: 10 });
  }
});

我所做的是通过将模型替换为来自 links 属性中指定的链接的数据来为我的博客创建分页机制。

我如何访问这个"links" 属性?


版本

  • ember @ 2.2
  • ember-data @ 2.2

【问题讨论】:

    标签: ember.js ember-data json-api


    【解决方案1】:

    解决方案

    我最终扩展了序列化程序并在记录数组规范化后将links 对象插入到meta 对象中。

    // 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 方法如何与符号交互。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多