1
1
import { Directive , Input , Self , AfterViewInit , HostListener } from '@angular/core' ;
2
-
3
- import { services } from 'typescript-angular-utilities' ;
4
- import __timeout = services . timeout ;
2
+ import { Observable , Subject } from 'rxjs' ;
5
3
6
4
import { FormComponent } from '../../components/form/form' ;
7
5
import { AutosaveActionService } from '../../services/autosaveAction/autosaveAction.service' ;
@@ -16,44 +14,51 @@ export class AutosaveDirective implements AfterViewInit {
16
14
@Input ( ) saveWhenInvalid : boolean ;
17
15
@HostListener ( 'keyup' ) keyupListener = this . resetDebounce ;
18
16
19
- timer : __timeout . ITimeout ;
20
17
form : FormComponent ;
21
- timeoutService : __timeout . TimeoutService ;
22
18
autosaveAction : AutosaveActionService ;
23
19
20
+ autosaveStart$ : Subject < void > = new Subject < void > ( ) ;
21
+ autosaveCancel$ : Subject < void > = new Subject < void > ( ) ;
22
+
24
23
constructor ( @Self ( ) form : FormComponent
25
- , timeoutService : __timeout . TimeoutService
26
24
, autosaveAction : AutosaveActionService ) {
27
25
this . form = form ;
28
- this . timeoutService = timeoutService ;
29
26
this . autosaveAction = autosaveAction ;
30
27
}
31
28
32
29
ngAfterViewInit ( ) : void {
33
30
this . form . form . statusChanges . subscribe ( this . setDebounce ) ;
34
31
}
35
32
33
+ ngOnDestroy ( ) : void {
34
+ this . autosaveCancel$ . next ( ) ;
35
+ }
36
+
36
37
setDebounce = ( ) : void => {
37
- if ( ! this . timer && this . form . dirty && ( this . saveWhenInvalid || this . form . validate ( ) ) ) {
38
- this . timer = this . timeoutService . setTimeout ( this . autosave , DEFAULT_AUTOSAVE_DEBOUNCE )
39
- . catch ( ( ) => null ) ;
38
+ 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 ( ) ;
40
44
}
41
45
}
42
46
43
47
resetDebounce ( ) : void {
44
- if ( this . timer ) {
45
- this . timer . cancel ( ) ;
46
- this . timer = null ;
47
- this . setDebounce ( ) ;
48
+ if ( this . canAutosave ( ) ) {
49
+ this . autosaveStart$ . next ( ) ;
48
50
}
49
51
}
50
52
51
53
autosave = ( ) : void => {
54
+ if ( ! this . canAutosave ( ) ) {
55
+ return ;
56
+ }
57
+
52
58
const waitOn = this . submitAndWait ( ) ;
53
59
if ( waitOn ) {
54
60
this . autosaveAction . trigger ( waitOn ) ;
55
61
}
56
- this . timer = null ;
57
62
}
58
63
59
64
submitAndWait ( ) : IWaitValue < any > {
@@ -63,4 +68,8 @@ export class AutosaveDirective implements AfterViewInit {
63
68
return this . form . submitAndWait ( ) ;
64
69
}
65
70
}
71
+
72
+ private canAutosave ( ) : boolean {
73
+ return this . form . dirty && ( this . saveWhenInvalid || this . form . validate ( ) ) ;
74
+ }
66
75
}
0 commit comments