如何访问控制器ember.js中的参数

Gir*_*ker 5 ember.js

这是我的router.js代码.

this.route('contact',{'path': '/contact/:chat_id'});
Run Code Online (Sandbox Code Playgroud)

这是我的route.js代码.

model(params) {

  return this.store.findRecord("chat", params.chat_id)
},
Run Code Online (Sandbox Code Playgroud)

这是我的controller.js代码,我可以像这样使用.它显示错误为空值请帮助我.如何在控制器中使用params

recordChat: function() {

  var chat = this.get(params.chat_id)

  Ember.RSVP.hash({
    offer_id: chat,
  })
}
Run Code Online (Sandbox Code Playgroud)

Cam*_*ron 7

我认为最简单的答案是在路由中创建一个变量,然后在setupController中设置它:

your_route.js

export default Ember.Route.extend({
  model(params) {
    this.set('myParam',params.my_Params);

    // Do Model Stuff...
  },
  setupController(controller, model) {
    // Call _super for default behavior
    this._super(controller, model);
    // Implement your custom setup after
    controller.set('myParam', this.get('myParam'));
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 这里`controllerFor`不是必需的,你可以说`controller.set(` (2认同)
  • 我必须承认不喜欢 model() 挂钩设置这样的东西,因为它的目的只是返回模型 (2认同)

Rem*_*rra 3

在你的route.js中,你需要像这样调用setupController函数:

setupController(controller, model) {
    this._super(...arguments);
    controller.set('chat', model);
}
Run Code Online (Sandbox Code Playgroud)

现在您可以通过调用以下命令在控制器中访问它:

recordChat() {
   const chat = this.get('chat');
   //  if you don't call the setupController function, you could also do:
   // const chat = this.get('model') or this.get('model.id') if you want the id only
}
Run Code Online (Sandbox Code Playgroud)

更新:

请参阅此处的工作旋转