本文介绍了使用Ember Data处理服务器端验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



当出现验证错误时,API返回代码422.然后Ember数据触发



从这里,我不知道什么是最好的方法来处理我正在收到错误,以及如何让他们冒泡起来。

  App.Challenge = DS.Model.extend Ember.Validations,
标题:attr('string')
摘要:attr('string')
#其他属性

becomeInvalid:(errors) - > ;
#这是我应该处理错误的地方吗?
#我怎么会让错误冒泡到这里呢?

我有2个问题。




  • 我不知道如果 becomeInvalid 是处理错误的地方,如果是,如何使错误显示在视图中

  • becomeInvalid @get('isValid')返回<$ c $

解决方案

是的。但你可能根本不需要做任何事情。 Ember数据预计您的api会在其json响应中包含任何验证错误。该错误对象被传递给 becomeInvalid 钩子,并在模型上另存为属性错误。所以如果你想要做的就是在你的视图中显示错误,可能就可以这样做:

  {{输入值= firstName}}< p class =inline-help> {{errors.firstName}}< / p> 

请参阅:

同意这很奇怪。我认为这是一个绑定的东西,就像在绑定更新之前,gotInvalid钩子正在运行。


I'm having trouble handling server side validations with Ember and Ember Data.

When a validation error occurs, the API returns the code 422. Ember data then triggers the becameInvalid callback on the model.

From here, I'm not sure what's the best way to handle the errors I'm getting, and how to make them bubble up to the view.

App.Challenge = DS.Model.extend Ember.Validations,
    title: attr('string')
    summary: attr('string')
    # other attributes

    becameInvalid: (errors) ->
        # is it the place where I should handle the errors?
        # how would I make the errors bubble up to the view here?

I have 2 issues.

  • I'm not sure if becameInvalid is the place to handle the errors, and if it is, how to make the errors display in the view
  • In becameInvalid, @get('isValid') returns true, which doesn't make sense to me.

解决方案

Yes. But you might not need to do anything at all. Ember-data expects your api to have included any validation errors in it's json response. That errors object is passed to the becameInvalid hook and also saved as a property errors on the model. So if all you want to do is display the errors in your view, it might be enough to do something like:

{{input value=firstName}}<p class="inline-help">{{errors.firstName}}</p>

See: https://github.com/emberjs/data/blob/master/packages/ember-data/lib/serializers/rest_serializer.js#L50-L61

Agreed that's weird. I think it's a bindings thing, like the becameInvalid hook is running before bindings have updated.

这篇关于使用Ember Data处理服务器端验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 00:10