![](/img/trans.png)
[英]How do i drill into any model from the store inside a controller or a route in ember.js?
[英]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();
// ...
還有一件事,訪問 store 可能應該使用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');
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.