【问题标题】:Cache data from external api with rails or ember?使用rails或ember缓存来自外部api的数据?
【发布时间】:2014-05-13 05:26:30
【问题描述】:

我有一个 ember/rails 应用程序,其中包含三个主要模板:主页、联系人和付款。联系人和付款模板都需要一组联系人。该数组需要从外部 api 填充。目前,对于每次我访问此模板的联系人,都会点击外部 api。理想情况下,我希望在用户首次登录时异步访问 api,获取该数据一次,然后在必要时无需访问外部 api 即可引用它。

使用 rails,我可以轻松地为具有 postgres json 列的用户添加 has_one :contacts_list,并在切换模板时根据需要有条件地刷新它。我很好奇在 ember 中处理这个问题的最佳方法。

【问题讨论】:

  • 您使用的是 ember 数据还是普通的旧 ajax?
  • 我正在使用 ember 数据。

标签: ruby-on-rails api postgresql caching ember.js


【解决方案1】:

您应该为 'contact' 创建一个 DS.Model 并在 Contacts and Payments 模型上使用 has_many。然后,您可以指定 'async: true' 之类的

DS.hasMany('contact', {async: true}),

如果联系人尚未加载,这将异步加载联系人。如果它们已加载,它将简单地返回加载的联系人。

我假设您有以下模型:联系人、付款。

【讨论】:

  • 是的,我有这些模型,但确实 currentUser 有_many 联系人和付款。例如,如果我设置了 async: true has_many 关系关闭 currentUser 并且我的 rails contacts 索引操作有此代码 Venmo.new(current_user.venmo_token, current_user.venmo_id).get_contacts.to_json 这个方法只会被点击一次然后缓存在 ember 中?
  • 所以如果你有像'currentUser'、'contacts'和'payments'这样的模型并且在模型中指定的联系人和支付上都有has_many,那么在这些上指定async true只会加载它们当您的代码尝试访问其中的某些内容(例如 currentUser.payments.length)时,如果尚未加载付款,则会对您的付款/索引操作发出 ajax 请求。
【解决方案2】:

我在路由上使用了setupController 方法来执行这种类型的缓存。只需检查内容是否已经可用,如果不存在则仅加载它。像这样的:

App.ContactsRoute = Ember.Route.extend({
  setupController : function(controller,model){
    if(!controller.get('content')){
      this.store.find('contact').then(function(contacts){
        controller.set('content',contacts)
      });
    }
  }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-07
    • 2018-01-29
    • 1970-01-01
    • 2016-05-17
    • 2019-12-23
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    相关资源
    最近更新 更多