无法在Ember 2中显示错误

时间:2015-11-22 00:30:01

标签: ember.js

在使用Ember 2.1.0构建的应用程序中,我遵循this guide来实现服务器端验证。

我有这条路线:

import Ember from 'ember';

export default Ember.Route.extend({
  model(params) {
    return this.store.findRecord('user', params.id);
  },
  actions: {
    submit: function() {
      this.controller.model.save().then(function() {
        this.transitionTo('admin.users');
      }, (data) => {
        console.log(data.errors);
        this.set('errors', data.errors);
      });
    },
    cancel: function() {
      this.controller.model.rollbackAttributes();
      this.transitionTo('admin.users');
    }
  }
});

我在模板中有这个代码:

  {{#if errors.length}}
    <div class='alert alert-danger'>
      <h4>There was a problem</h4>
      <p>The user could not be saved due to validation errors</p>
    </div>
  {{/if}}

服务器返回{"errors":[{"email":["can't be blank"]}]},错误显示在控制台中,但页面上没有任何内容。

根据the documentation,我尝试返回{"errors":{"email":["can't be blank"]}},但我有#34; InvalidError期望json-api格式化错误数组。&#34;

如何在Ember 2中显示错误?

1 个答案:

答案 0 :(得分:1)

我终于找到了解决方案。服务器发送的数据不使用the doc中所写的json API格式,如下所示:

HTTP/1.1 422 Unprocessable Entity
Content-Type: application/vnd.api+json

{
  "errors": [
    {
      "status": "422",
      "source": { "pointer": "/data/attributes/first-name" },
      "title":  "Invalid Attribute",
      "detail": "First name must contain at least three characters."
    }
  ]
}

我在ruby中编写了这段代码,以便正确格式化:

class ErrorSerializer
  def self.serialize(errors)
    result = errors.messages.map do |message|
      message.last.map do |detail|
        {
          "source": { "pointer": "/data/attributes/#{message.first}" },
          "detail": detail
        }
      end
    end.flatten
    { errors: result }
  end
end

我可以像这样使用:

render status: :unprocessable_entity, json: ErrorSerializer.serialize(user.errors)