I'm new to angular. I was trying something and got stuck. In my form, I want to show server validation response as error coming from a laravel rest api. But don't know how to store and show it in the template. I am able to log it to the console but not able to move further with the error message.
The response is somewhat like this-
{
"message": {
"firstname":["The firstname field is required."],
"lastname":["The lastname field is required."],
"email":["The email field is required."],
"password":["The password field is required."]
}
}
The Service code:
registerUser(user): Observable<any> {
return this.http
.post<any>(`${this.url}/register`, user)
.pipe(map(res => res.message));
}
The register user method in component class:
registerUser() {
console.log(this.registrationForm.value);
this.authService.registerUser(this.registrationForm.value).subscribe(
res => console.log(res),
err => console.log(err)
);
}
Also, correct me if I'm going wrong anywhere and how should I correct it
My understanding is that you'll like to display the error messages on each field that failed a validation, i have done that some times.
The shared approach handles the following:
The general idea is to create a reusable service that knows how to detect errors and how to add them to the reactive forms, this service can handle client and server errors, let's call it ErrorService
, this service can have a function like renderServerErrors(form: FormGroup, response: ErrorResponse)
which gets invoked on each server response and verify whether there is any error to render in the form.
An error is rendered into the form is the form has the given field.
You can see the following files to guide you:
If you pay attention, the error responses are handled with this.errorService.renderServerErrors(this.form, response)
which does everything, see it live at https://cryptocoinalerts.net/login.
Some more details
err => console.log(err)
), if this assumption is not true, you'll need another check to verify if there is any error on the response.{
"errors": [
{
"type": "field-validation-error",
"field": "password",
"message": "Incorrect password"
}
]
}
Feel free to ask if anything is not clear.