引用http://emberjs.com/api/data/classes/DS.Errors.html
我有一条路线checkout.address
,可以呈现app/templates/checkout/address.hbs
。它具有以下内容:
当我尝试使用无效值创建或更新地址时。应用程序抱怨,因为API返回验证错误。这是预期的。 Ember-Inspector中的Network
选项卡确认API以以下形式返回错误:
errors: Object
street: Array
0: can't be blank
但是,错误不会显示在任何一种表单上。我本来期望下面这行可以做到这一点:
{{#each error in errors.street}}
<br />{{error.message}}
{{/each}}
我做错了什么?
代码:
// app/router.js
import Ember from 'ember';
import config from './config/environment';
var Router = Ember.Router.extend({
location: config.locationType
});
Router.map(function() {
this.route('checkout', function() {
this.route('address');
});
});
export default Router;
// app/controllers/checkout/address.js
import Ember from 'ember';
// export default Ember.ArrayController.extend({
export default Ember.ObjectController.extend({
actions: {
create: function() {
var _this = this;
// this.get('model').save().then(function(address){
this.store.createRecord('address', {
street: this.get('street')
}).save().then(function(address){
// address.save().then(function(address){
_this.transitionToRoute('addresses.index', address);
}, function(errors) {
// console.log(errors);
// Need this promise, so we can render errors, if any, in the form
// console.log('error');
});
},
update: function(address) {
var _this = this;
address.set("street", address.get('street'));
address.save().then(function(){
_this.transitionToRoute('checkout.address');
}, function() {
console.log('here');
// Need this promise, so we can render errors, if any, in the form
});
return false;
}
}
});
// app/templates/checkout/address.hbs
<h1>Addresses</h1>
<p>Create address:</p>
<form {{action "create" on="submit"}}>
<p>
<label>Street:
{{input value=street placeholder="Foo street"}}
</label>
{{#each error in errors.street}}
<br />{{error.message}}
{{/each}}
</p>
<input type="submit" value="Create"/>
</form>
<ul>
{{#each model}}
<li>
Address: {{street}}
<form {{action "update" this on="submit"}}>
<label>street:
{{input value=street placeholder="Foo Street"}}
</label>
{{#each error in errors.street}}
<br />{{error.message}}
{{/each}}
</p>
<input type="submit" value="Update"/>
</form>
</li>
{{/each}}
</ul>
答案 0 :(得分:0)
首先,您使用的是哪个适配器? DS.Errors在ActiveRecordsAdapter中是默认的。如果您正在使用RESTAdapter,则必须首先实现它。
我认为您需要将错误设置为控制器上的属性。尝试做:
this.set('errors',errors);
在保存返回的承诺的错误处理程序中。