[英]Display validation error messages (Spring Boot, Angular CLI 7)
我正在尝试显示从后端(Spring Boot)传递到前端(Angular CLI 7)的错误。 错误由 ResponseEntity 传递。
我有一个检查响应的 function
OnRegister(user) {
this.errorMessages = [];
this.authenticationService.register(user)
.subscribe(resp => {
this.router.navigateByUrl('/pages/authentication/login');
}, error => this.errorMessages.push(error.error)
);
console.log(this.errorMessages);
}
数组 errorMessages 保存“ValidationMessage”对象 - 字段:字段、消息。
控制台 output:
[]
0: Array(3)
0: {field: "password", message: "Field password cannot be null."}
1: {field: "passwordConfirm", message: "Field passwordConfirm cannot be null."}
2: {field: "email", message: "Field email cannot be null."}
我怎样才能从这个数组中获取一个元素。
不能只使用:
<li *ngFor="let error of errorMessages">
<p>{{error.message}}</p>
</li>
您需要将来自 spring 的消息迭代到 string[] state 命名错误中。
error: (error: (any)) => {
let errors = error.error.errors;
for (let i = 0; i < errors.length; i++) {
this.error.push(errors[i].field + " " + errors[i].message);
}
}
然后,您可以像这样在组件 html 中显示它们
<div class="alert alert-danger" role="alert">
<ul>
<li *ngFor="let error of error">{{error}}</li>
</ul>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.