【问题标题】:Ember JS - updating model property when fetching records after route has loadedEmber JS - 在路由加载后获取记录时更新模型属性
【发布时间】:2017-10-12 14:16:37
【问题描述】:

假设我的路线中有以下代码:

model() {
  return this.get('store').query('post', { author: 'John' });
},

actions: {
  fetchNewPosts: function() {
    this.get('store').query('post', { author: 'Sally' });
  }
}

然后在一个组件中如下:

modelSubset: function() {
  return this.get('model').slice(0, 10);
}.property('model', 'model.@each'),

当输入路由时,组件中的计算属性会更新良好,并且作者“John”的帖子会在模型挂钩中获取。

但是,如果我稍后触发 fetchNewPosts 操作,则会获取记录并将其添加到 Ember 数据中,但组件中的计算属性不会更新。

有没有办法获取新记录以更新模型属性?

【问题讨论】:

    标签: javascript ember.js


    【解决方案1】:

    正如kumkanillam 所提到的,我需要使用查询参数来实现这一点。以下是我的新模式:

    将“作者”定义为控制器中的查询参数。

    queryParams: ['author',],
      author: "John",

    在路由的模型钩子中,params.author 从控制器中获取值。在fetchJobs 操作中,我使用transitionTo 来更新查询参数。

    model(params) {
        return this.get('store').query('posts', { author: params.author });
    },
    
    actions: {
      fetchJobs: function(authorName) {
        this.transitionTo({ queryParams: { author: authorName }});
      }
    },

    当查询参数改变时,下面的代码会导致模型更新。

    queryParams: {
      author: {
        refreshModel: true
      }
    }

    【讨论】:

      【解决方案2】:

      这里您没有更改model 属性,因此计算的属性将不会运行。 所以你需要更新model属性,

      fetchNewPosts: function() {
          this.get('store').query('post', { author: 'Sally' }).then(result=>{
            this.set('model',result);
           });
        }
      

      您的计算属性依赖键应包括模型model.@each.propertyName 中的任何属性。

      注意:在您的情况下,我更喜欢使用dynamic segments 或query params 方法。

      【讨论】:

      • 我无法让上述工作,但我将模型挂钩更改为return this.get('store').findAll('post');,然后将 API 设置为仅发送 John 的帖子。然后这段代码:this.get('store').query('post', { author: 'Sally' }); 获取额外的帖子,并更新模型而无需显式设置。不知何故,在模型钩子中使用 findAll 而不是查询,使模型属性自动识别新记录。
      • 显然this.get('store').findAll('post'); and then set the API to only send posts by John 这是错误的做法。 findAll 应该始终返回所有数据,这就是 ember 的假设方式。究竟是什么不起作用?
      • 用您更新/尝试过的代码更新问题,这将有所帮助
      • 您使用查询参数的建议是正确的做法。
      猜你喜欢
      • 2015-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多