9
9
Output ,
10
10
SimpleChanges
11
11
} from '@angular/core' ;
12
+ import { fromEvent , Subscription } from 'rxjs' ;
13
+ import { filter , startWith , switchMap } from 'rxjs/operators' ;
12
14
import { MapService } from '../map/map.service' ;
13
15
import { MapImageData , MapImageOptions } from '../map/map.types' ;
14
16
@@ -28,40 +30,22 @@ export class ImageComponent implements OnInit, OnDestroy, OnChanges {
28
30
@Output ( ) error = new EventEmitter < { status : number } > ( ) ;
29
31
@Output ( ) loaded = new EventEmitter < void > ( ) ;
30
32
31
- private imageAdded = false ;
33
+ private isAdded = false ;
34
+ private isAdding = false ;
35
+ private sub : Subscription ;
32
36
33
37
constructor (
34
38
private MapService : MapService ,
35
39
private zone : NgZone
36
40
) { }
37
41
38
42
ngOnInit ( ) {
39
- this . MapService . mapLoaded$ . subscribe ( async ( ) => {
40
- if ( this . data ) {
41
- this . MapService . addImage (
42
- this . id ,
43
- this . data ,
44
- this . options
45
- ) ;
46
- this . imageAdded = true ;
47
- } else if ( this . url ) {
48
- try {
49
- await this . MapService . loadAndAddImage (
50
- this . id ,
51
- this . url ,
52
- this . options
53
- ) ;
54
- this . imageAdded = true ;
55
- this . zone . run ( ( ) => {
56
- this . loaded . emit ( ) ;
57
- } ) ;
58
- } catch ( error ) {
59
- this . zone . run ( ( ) => {
60
- this . error . emit ( error ) ;
61
- } ) ;
62
- }
63
- }
64
- } ) ;
43
+ this . sub = this . MapService . mapLoaded$ . pipe (
44
+ switchMap ( ( ) => fromEvent ( < any > this . MapService . mapInstance , 'styledata' ) . pipe (
45
+ startWith ( undefined ) ,
46
+ filter ( ( ) => ! this . isAdding && ! this . MapService . mapInstance . hasImage ( this . id ) )
47
+ ) ) ,
48
+ ) . subscribe ( ( ) => this . init ( ) ) ;
65
49
}
66
50
67
51
ngOnChanges ( changes : SimpleChanges ) {
@@ -76,8 +60,41 @@ export class ImageComponent implements OnInit, OnDestroy, OnChanges {
76
60
}
77
61
78
62
ngOnDestroy ( ) {
79
- if ( this . imageAdded ) {
63
+ if ( this . isAdded ) {
80
64
this . MapService . removeImage ( this . id ) ;
81
65
}
66
+ if ( this . sub ) {
67
+ this . sub . unsubscribe ( ) ;
68
+ }
69
+ }
70
+
71
+ private async init ( ) {
72
+ this . isAdding = true ;
73
+ if ( this . data ) {
74
+ this . MapService . addImage (
75
+ this . id ,
76
+ this . data ,
77
+ this . options
78
+ ) ;
79
+ this . isAdded = true ;
80
+ this . isAdding = false ;
81
+ } else if ( this . url ) {
82
+ try {
83
+ await this . MapService . loadAndAddImage (
84
+ this . id ,
85
+ this . url ,
86
+ this . options
87
+ ) ;
88
+ this . isAdded = true ;
89
+ this . isAdding = false ;
90
+ this . zone . run ( ( ) => {
91
+ this . loaded . emit ( ) ;
92
+ } ) ;
93
+ } catch ( error ) {
94
+ this . zone . run ( ( ) => {
95
+ this . error . emit ( error ) ;
96
+ } ) ;
97
+ }
98
+ }
82
99
}
83
100
}
0 commit comments