1
1
import { Directive , Input , Self , AfterViewInit , HostListener } from '@angular/core' ;
2
- import { Observable , Subject } from 'rxjs' ;
3
2
4
3
import { FormComponent } from '../../components/form/form' ;
5
4
import { AutosaveActionService } from '../../services/autosaveAction/autosaveAction.service' ;
@@ -14,12 +13,10 @@ export class AutosaveDirective implements AfterViewInit {
14
13
@Input ( ) saveWhenInvalid : boolean ;
15
14
@HostListener ( 'keyup' ) keyupListener = this . resetDebounce ;
16
15
16
+ timer : any ;
17
17
form : FormComponent ;
18
18
autosaveAction : AutosaveActionService ;
19
19
20
- autosaveStart$ : Subject < void > = new Subject < void > ( ) ;
21
- autosaveCancel$ : Subject < void > = new Subject < void > ( ) ;
22
-
23
20
constructor ( @Self ( ) form : FormComponent
24
21
, autosaveAction : AutosaveActionService ) {
25
22
this . form = form ;
@@ -31,34 +28,34 @@ export class AutosaveDirective implements AfterViewInit {
31
28
}
32
29
33
30
ngOnDestroy ( ) : void {
34
- this . autosaveCancel$ . next ( ) ;
31
+ if ( this . timer ) {
32
+ clearTimeout ( this . timer ) ;
33
+ }
35
34
}
36
35
37
36
setDebounce = ( ) : void => {
38
37
if ( this . canAutosave ( ) ) {
39
- this . autosaveCancel$ . next ( ) ;
40
- this . autosaveStart$ . debounceTime ( DEFAULT_AUTOSAVE_DEBOUNCE ) . takeUntil ( this . autosaveCancel$ ) . subscribe ( ( ) => this . autosave ( ) ) ;
41
- this . autosaveStart$ . next ( ) ;
42
- } else {
43
- this . autosaveCancel$ . next ( ) ;
38
+ if ( ! this . timer && this . form . dirty && ( this . saveWhenInvalid || this . form . validate ( ) ) ) {
39
+ this . timer = setTimeout ( this . autosave , DEFAULT_AUTOSAVE_DEBOUNCE )
40
+ }
44
41
}
45
42
}
46
43
47
44
resetDebounce ( ) : void {
48
- if ( this . canAutosave ( ) ) {
49
- this . autosaveStart$ . next ( ) ;
45
+ if ( this . timer && this . canAutosave ( ) ) {
46
+ clearTimeout ( this . timer ) ;
47
+ this . timer = null ;
48
+ this . setDebounce ( ) ;
50
49
}
51
50
}
52
51
53
52
autosave = ( ) : void => {
54
- if ( ! this . canAutosave ( ) ) {
55
- return ;
56
- }
57
-
58
- const waitOn = this . submitAndWait ( ) ;
59
- if ( waitOn ) {
60
- // subscribes to kick off the stream
61
- this . autosaveAction . waitOn ( waitOn ) . subscribe ( ) ;
53
+ if ( this . canAutosave ( ) ) {
54
+ const waitOn = this . submitAndWait ( ) ;
55
+ if ( waitOn ) {
56
+ this . autosaveAction . waitOn ( waitOn ) . subscribe ( ) ;
57
+ }
58
+ clearTimeout ( this . timer ) ;
62
59
}
63
60
}
64
61
@@ -71,6 +68,6 @@ export class AutosaveDirective implements AfterViewInit {
71
68
}
72
69
73
70
private canAutosave ( ) : boolean {
74
- return this . form . dirty && ( this . saveWhenInvalid || this . form . validate ( ) ) ;
75
- }
76
- }
71
+ return this . form . dirty && ( this . saveWhenInvalid || this . form . validate ( ) ) ;
72
+ }
73
+ }
0 commit comments