我有一个带有 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/