js -如何正确地从控制器调用store
Ember.js - How to properly call the store from a controller?
所以我试图从一个控制器访问商店,像这样:
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
注入controller
和route
。还有一件事你应该通过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');
});
}
相关文章:
- 由控制器调用的服务更改时,Angular未更新视图
- 概念验证模型控制器调用正确的实例
- 角度.js - 识别通过路由或 ng 控制器调用的控制器
- 在 angularJs 中从控制器调用同时$http服务
- 从另一个控制器调用一个控制器
- 在控制台中隐藏AJAX控制器调用
- 如何从指令的控制器调用依赖注入服务的嵌套方法
- 将全局变量从控制器调用到HTML视图AngularJS
- 将数据从控制器调用到HTML视图AngularJS
- 从 AngularJS 中的父控制器调用指令的方法
- 从 Angular 控制器调用引导模式
- 从控制器调用特定指令实例的函数
- 从另一个文件 AngularJS 中的另一个控制器调用函数
- 如何在 angularjs 中从一个控制器调用另一个控制器的函数
- AngularJS + Ionic - 如何从第一个控制器调用第二个控制器上的方法
- 如何从 Angular 上的控制器调用指令的函数
- AngularJS,ng-repeat+过滤器从控制器调用
- 使用链接从不同的控制器调用操作
- Angularjs,如何从另一个控制器调用控制器
- 根据条件从 Rails 控制器调用 jQuery 函数