json - Angular - FormGroup 显示来自服务器 Rest Api 的 json 错误

标签 json rest angular angular2-forms

我有一个带有 PHP 框架 Symfony 的 REST API 服务器,它返回此类消息:

{
  "code": 400,
  "message": "Validation Failed",
  "errors": {
    "children": {
      "email": {
        "errors": [
          "This address mail is already used."
        ]
      },
      "name": {
        "errors": [
          "This name is too short."
        ]
      },
      "password": []
    }
  }
}

在 Angular FormGroup 的正面,我有以下代码:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';

import { RegisterService } from './register.service';

@Component({
  selector: 'app-authentication',
  templateUrl: './authentication.component.html',
})
export class AuthenticationComponent {
    loginForm: FormGroup;
    error: string = '';

    constructor(
        private formBuilder: FormBuilder, 
        private registerService: RegisterService, 
        private router: Router
    ) {
        this.loginForm = formBuilder.group({
            'name': ['', Validators.required],
            'email': ['', Validators.required],
            'password': ['', Validators.required]
        });
    }

    onSubmit() {
        this.authenticationService
            .authenticate(this.loginForm.value)
            .subscribe(
                data => { 
                    localStorage.setItem('id_token', data.token);
                    this.router.navigate(['post']); 
                },
                error 
                => 
                // Do something
                // Display server json errors in the corresponding fields
            );
    }
}

如何从 REST API 获取每条错误消息并显示在相应字段下?

感谢您的帮助

最佳答案

这个答案与 Amit 的答案没有太大不同,但这里我们不是以相同的方式直接设置值,而是将错误存储在对象中。这可能可以进一步完善;)

formErrors = {}; // object to store error messages

 ...
(error : any) => {
    // get the nested errors
    let errorData = error.json().errors.children;
    // iterate the keys in errors
    for(let key in errorData) {
      // if key has nested "errors", get and set the error message, else set null
      errorData[key].errors ? this.formErrors[key]=errorData[key].errors[0] : this.formErrors[key] = null
    }
}

然后在您的模板中,您将只显示错误消息(如果存在):

<label>Name</label>
<input formControlName="name" />
<small *ngIf="formErrors.name">{{formErrors.name}}</small>

<label>Email</label>
<input formControlName="email" />
<small *ngIf="formErrors.email">{{formErrors.email}}</small>

<label>Password</label>
<input formControlName="password" />
<small *ngIf="formErrors.password">{{formErrors.password}}</small>

记住在每轮之后重置 formErrors 对象,以便您获得更新的值:)

关于json - Angular - FormGroup 显示来自服务器 Rest Api 的 json 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43938598/

相关文章:

django - 如何向 Django 中的模型添加临时字段?

javascript - 追加 2 个或更多 json 字符串

angular - "Type ' 对象 ' is not assignable to type"带有新的 HttpClient/HttpGetModule

objective-c - JSON 结果到 Objective-C 中的 NSDictionary

javascript - 在 JavaScript 中拆分定界字符串与 JSON 解析效率

java - Spring REST - 创建 ZIP 文件并将其发送到客户端

api - 如何启用 REST API 直接信用卡付款的实时凭证

rest - 为什么不是每次都使用基本身份验证而不是 JWT?

typescript - 使用 Electron 时,我应该如何为 Angular 2 配置基本 href?

angular - 如何重新初始化/重新触发使用动画系统制作的动画?