无法在控制器中的模型哈希上调用 forEach

Can't call forEach on model hash in controller

我有一条名为 tickets 的路线,其模型设置如下所示

model() {
  return Ember.RSVP.hash({
    event: null,
    tickets: null
  });
},
actions: {
  didTransition(){
    if(!this.controller.get('model.length')){
      new Ember.RSVP.hash({
        event: this.modelFor('events.event'),
        tickets: this.store.query('ticket',{user_id:this.get('user.user.user_id'),event_code:this.modelFor('events.event').get('event_code')})
      }).then((hash)=>{
        if(!hash.tickets.get('length')){
          this.controller.set('noTickets',true);
        }
        this.controller.set('model',hash);
      });
    }
  }
}

模板设法在 {{#each}}

中循环遍历这些 model.tickets

在我的控制器中,我试图设置一个 groupBy 计算,但在我的计算中我得到了错误

ticketsByPurchase: Ember.computed('model.tickets.[].ticket_purchase_code',function(){
    let tickets = this.get('model.tickets');
    tickets.forEach(function(ticket){
      console.log(ticket);
    });
  })

尝试防止 model.tickets 被迭代,在计算的 属性:

中使用类似这样的东西
if(!tickets){
  return Ember.A()
}else{
  //your forEach code here
}

或者在你的路线中:

  }).then((hash)=>{
    if(!hash.tickets.get('length')){
      this.controller.set('noTickets',true);
      hash.tickets = Ember.Array([])
      this.controller.set('model',hash);
    }else{
      this.controller.set('model',hash);
    }
  });

this.controller.get('model.length') 始终为空,因为模型是散列,而不是数组。另外 didTransition 不是一个动作,它是一个常规函数,所以如果在动作散列中定义它可能不会触发。

我建议删除对 didTransition 的调用,并像这样在模型挂钩中执行所有逻辑:

model() {
  let event = this.modelFor('events.event');
  let event_code = event.get('event_code');

  // this probably does not work, you have to get the user
  // from another route or a service.
  // this might work: this.controllerFor('user').get('user.user_id');
  let user_id = this.get('user.user.user_id');

  return Ember.RSVP.hash({
    event,
    tickets: this.store.query('ticket', { user_id, event_code })
  });
},

setupController(controller, model) {
  // super sets controller model to be route model.
  // ie. controller.set('model', model);
  this._super(...arguments);

  if (!model.get('tickets.length')) {
    controller.set('noTickets', true);
  }
}