Ember:将模型中的错误插入应用程序模板

时间:2017-03-14 10:31:10

标签: javascript ember.js model ember-data

我在模型类中看到了becomeError和becomeInvalid触发器,例如:

//model/car.js
example  import Ember from "ember";
import Model from "ember-data/model";

export default Model.extend({
  becameError() {
    alert('there was an error!');
  },

  becameInvalid(errors) {
    alert(`Record was invalid because: ${errors}`);
  },
});

现在,当我保存模型并且后端返回错误时,将显示警报。但是如何在应用程序模板中显示错误消息?

类似的东西:

becameError() {
    applcation.set('hasError', true);
  },

//application.hbs
{{#if hasError}}
   <h1>An error has occured!</h1>
{{/if}}

1 个答案:

答案 0 :(得分:2)

您可以使用service

//services/error-container.js
...
errors: Ember.A()
...

现在车型

//models/car.js
...
export default Model.extend({
  errorContainer: Ember.inject.service(),
  becameError() {
    alert('there was an error!');
    this.get('errorContainer.errors').pushObjects(this.get('errors'));
  }
...

并在申请模板中

//application.hbs
{{#if hasError}}
   {{#each errorContainer.errors as |error|}}
      <div>error.message</div>
   {{/each}}
{{/if}}

并在应用程序控制器中

...
errorContainer: Ember.inject.service(),
hasError: Ember.computed.notEmpty('errorContainer.errors')
...

此外,您还需要注意清除errors中的错误对象