1
1
import { Component , inject } from '@angular/core' ;
2
2
import { FormBuilder , Validators } from '@angular/forms' ;
3
+ import { FormErrorHandler , FormValidationError , FormValidationErrors , KLP_FORM_ERROR_HANDLER } from '@klippa/ngx-enhancy-forms' ;
4
+
5
+ // this is a little like an error from GQL.
6
+ type LocationErrors = {
7
+ kind : 'LOCATION_ERRORS' ,
8
+ errors : Array < {
9
+ message : any ,
10
+ location : Array < string > ;
11
+ } > ;
12
+ } ;
13
+
14
+ async function someApiCall ( value : { name : string , nested : { name : string } } ) {
15
+ const locationErrors : LocationErrors = {
16
+ kind : 'LOCATION_ERRORS' ,
17
+ errors : [ ] ,
18
+ } ;
19
+ if ( value . name !== 'bob' ) {
20
+ locationErrors . errors . push ( { location : [ 'name' ] , message : 'must be bob' } ) ;
21
+ }
22
+
23
+ if ( value . nested . name === 'fred' ) {
24
+ locationErrors . errors . push ( { location : [ 'nested' , 'name' ] , message : 'cannot be fred' } ) ;
25
+ }
26
+
27
+ throw locationErrors ;
28
+ }
29
+
30
+ const LocationErrorHandler : FormErrorHandler = ( error : any ) : FormValidationErrors => {
31
+ if ( error ?. kind === 'LOCATION_ERRORS' ) {
32
+ return ( error as LocationErrors ) . errors . map ( e => new FormValidationError (
33
+ e . location . join ( '.' ) ,
34
+ e . message ,
35
+ ) ) ;
36
+ }
37
+
38
+ throw error ;
39
+ } ;
3
40
4
41
@Component ( {
5
42
selector : 'app-on-submit-errors' ,
6
43
templateUrl : './on-submit-errors.component.html' ,
7
- styleUrls : [ './on-submit-errors.component.scss' ]
44
+ styleUrls : [ './on-submit-errors.component.scss' ] ,
45
+ providers : [
46
+ { provide : KLP_FORM_ERROR_HANDLER , useValue : LocationErrorHandler } ,
47
+ ]
8
48
} )
9
49
export class OnSubmitErrorsComponent {
10
50
private fb = inject ( FormBuilder ) ;
@@ -25,22 +65,11 @@ export class OnSubmitErrorsComponent {
25
65
) ;
26
66
}
27
67
28
- protected onSubmit = async ( value : any ) => {
29
- const err : any = { } ;
30
- if ( value . name !== 'bob' ) {
31
- err . name = 'must be bob' ;
32
- }
33
-
34
- if ( value . nested . name === 'fred' ) {
35
- err [ 'nested.name' ] = 'cannot be fred' ;
36
- }
37
-
38
- if ( value . nested . name !== 'greg' ) {
39
- err . nested = {
40
- name : 'cannot be fred'
41
- } ;
42
- }
68
+ protected beforeSubmit = async ( ) => {
69
+ throw new Error ( 'bar' ) ;
70
+ }
43
71
44
- throw err ;
72
+ protected onSubmit = async ( value : any ) => {
73
+ await someApiCall ( value ) ;
45
74
}
46
75
}
0 commit comments