js -如何正确地从控制器调用store

Ember.js - How to properly call the store from a controller?

本文关键字:控制器 调用 store 正确地 js      更新时间:2023-09-26

所以我试图从一个控制器访问商店,像这样:

import Ember from 'ember';
export default Ember.Controller.extend({
  emailAddress: '',
  message: '',
  isValidEmail: Ember.computed.match('emailAddress', /^.+@.+'..+$/),
  isMessageLongEnough: Ember.computed.gte('message.length', 10),
  isValid: Ember.computed.and('isValidEmail', 'isMessageLongEnough'),
  isNotValid: Ember.computed.not('isValid'),
  actions: {
    sendConfirmation() {
      this.store.createRecord('contact', {
        email: emailAddress,
        message: message,
      }).save();
      this.set('responseMessage', 'We got your message and we will be in contact soon :)');
      this.set('emailAddress', '');
      this.set('message', '');
    }
  }
});

我看了Ember.js 2.7的文档,它没有特别告诉你在哪里可以访问商店,但我知道可以通过控制器或路由访问它。

然而,这样做会给我这些错误:

controllers/contact.js: line 17, col 16, 'emailAddress' is not defined.
controllers/contact.js: line 18, col 18, 'message' is not defined.

我不确定这是我访问控制器的方式,还是我定义emailAddress和message的方式。

请帮忙,谢谢!

解决:对于这部分:

sendConfirmation() {
    this.store.createRecord('contact', {
    email: emailAddress,
    message: message,
 }).save();

应该是这样的:

sendConfirmation() {
    this.store.createRecord('contact', {
    email: this.get('emailAddress'),
    message: this.get('message'),
  }).save();

:)

您的问题不在于您访问存储的方式,而在于您试图添加带有电子邮件和消息的联系人,而没有实际定义变量。

sendConfirmation() {
  this.store.createRecord('contact', {
    // what do you expect emailAddress and message values to be at this point?
    email: emailAddress, // <-- emailAddress is not defined
    message: message,    // <-- message is not defined
  }).save();
  // ...

你是不是想先把它们找回来?

sendConfirmation() {
  // retrieve emailAddress and message first
  const { 
    emailAddress, 
    message 
  } = this.getProperties('emailAddress', 'message');
  // then use them to create a contact
  this.store.createRecord('contact', {
    email: emailAddress
    message: message
  }).save();
  // ...

还有一件事,访问存储可能应该使用this.get('store'),因为使用getter/setter是访问/操作属性的最后方式。

默认将store注入controllerroute。还有一件事你应该通过get

设置属性
sendConfirmation() {
    var newRecordObj = {};
    newRecordObj['email'] = this.get('emailAddress');
    newRecordObj['message'] = this.get('message');
    this.get('store').createRecord('contact', newRecordObj).save((result) => {
        //success handling 
        this.set('responseMessage', 'We got your message and we will be in contact soon :)');
        this.set('emailAddress', '');
        this.set('message', '');
    }, () => {
        //error handling
        this.set('responseMessage', 'Error message');
    });
}