Last active
May 14, 2022 06:54
-
-
Save wh0th3h3llam1/16e918c8bed20c30eb9124822405a598 to your computer and use it in GitHub Desktop.
Error Service to render form errrors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { HttpErrorResponse } from '@angular/common/http'; | |
import { Injectable } from '@angular/core'; | |
import { FormGroup } from '@angular/forms'; | |
import { Router } from '@angular/router'; | |
import { NzMessageService } from 'ng-zorro-antd/message'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class ErrorService { | |
constructor(private message: NzMessageService, private router: Router) { } | |
resolveServerErrors(response: HttpErrorResponse, form?: FormGroup) { | |
if (response.status === 400 && form) { | |
return this.renderFormErrors(form, response) | |
} | |
else if (response.status === 403) { | |
... | |
} | |
else if (response.status === 404) { | |
... | |
} | |
else if (response.status === 500) { | |
... | |
} | |
} | |
renderFormErrors(form: FormGroup, response: HttpErrorResponse) { | |
Object.keys(response.error).forEach(prop => { | |
const formControl = form.get(prop); | |
if (formControl) { | |
// activate the error message | |
formControl.setErrors({ | |
serverError: response.error[prop] | |
}); | |
} | |
}) | |
this.message.remove(); | |
this.message.warning("Resolve form errors & try again!", {nzDuration: 8000}) | |
if (response.error.non_field_errors) { | |
return response.error.non_field_errors | |
} | |
return undefined | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment