简体   繁体   English

显示验证错误消息(Spring Boot,Angular CLI 7)

[英]Display validation error messages (Spring Boot, Angular CLI 7)

I'am trying to display errors passed from backend (Spring Boot) to frontend (Angular CLI 7).我正在尝试显示从后端(Spring Boot)传递到前端(Angular CLI 7)的错误。 Errors are passed on by the ResponseEntity.错误由 ResponseEntity 传递。

I have a function that check for response我有一个检查响应的 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);
    }

Array errorMessages hold "ValidationMessage" objects - fields: field, message.数组 errorMessages 保存“ValidationMessage”对象 - 字段:字段、消息。

Console output:控制台 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."}

How can i get an element from this array.我怎样才能从这个数组中获取一个元素。

It's not possible to use just:不能只使用:

<li *ngFor="let error of errorMessages">
  <p>{{error.message}}</p>
</li>

You need to iterate the message from spring into the string[] state named error.您需要将来自 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);
          }
        }

And then, you can show them in the your component html like this然后,您可以像这样在组件 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM