我正在寻找一种优雅的方式来显示来自服务器端API的验证消息,而无需在UI中创建自定义验证器或硬编码所有可能的消息。
我需要将错误消息添加到特定字段以及整个表单。
这必须适用于Angular 2.0.0-beta.3
答案 0 :(得分:22)
有两种服务器验证:
对于那个,只需从响应有效负载中提取消息并将其放入组件的属性中,以将其显示在关联的模板中:
@Component({
(...)
template: `
<form (submit)="onSubmit()">
(...)
<div *ngIf="errorMessage">{{errorMessage}}</div>
<button type="submit">Submit</button>
</form>
`
})
export class MyComponent {
(...)
onSubmit() {
this.http.post('http://...', data)
.map(res => res.json())
.subscribe(
(data) => {
// Success callback
},
(errorData) => {
// Error callback
var error = errorData.json();
this.error = `${error.reasonPhrase} (${error.code})`;
}
);
}
}
我假设错误的响应有效负载是JSON,并且对应于以下内容:
{
"code": 422,
"description": "Some description",
"reasonPhrase": "Unprocessable Entity"
}
对于第二个,您可以在与表单输入关联的控件中设置收到的错误消息,如下所述:
@Component({
(...)
template: `
<form [ngFormModel]="myForm" (submit)="onSubmit()">
(...)
Name: <input [ngFormControl]="myForm.controls.name"/>
<span *ngIf="myForm.controls.name.errors?.remote"></span>
(...)
<button type="submit">Submit</button>
</form>
`
})
export class MyComponent {
(...)
constructor(builder:FormBuilder) {
this.myForm = this.companyForm = builder.group({
name: ['', Validators.required ]
});
}
onSubmit() {
this.http.post('http://...', data)
.map(res => res.json())
.subscribe(
(data) => {
// Success callback
},
(errorData) => {
// Error callback
var error = errorData.json();
var messages = error.messages;
messages.forEach((message) => {
this.companyForm.controls[message.property].setErrors({
remote: message.message });
});
}
);
}
}
我假设错误的响应有效负载是JSON,并且对应于以下内容:
{
messages: [
{
"property": "name",
"message": "The value can't be empty"
]
}
有关详细信息,您可以查看此项目:
答案 1 :(得分:3)
我向您展示了权威的displayErrors函数(处理 JSONAPI 标准后的服务器端验证):
您需要Underscore.js
displayErrors(error: ErrorResponse) {
let controls = this.supportRequestForm.controls;
let grouped = _.groupBy(error['errors'], function(e) {
return e['source']['pointer'];
});
_.each(grouped, function(value, key, object) {
let attribute = key.split('/').pop();
let details = _.map(value, function(item) { return item['detail']; });
controls[attribute].setErrors({ remote: details.join(', ') });
});
}