Issue
I have this service:
@Injectable({
providedIn: 'root',
})
export class BackgroundLayersService {
private mapSubject = new BehaviorSubject<Map | null>(null);
map$: Observable<Map | null> = this.mapSubject.asObservable();
constructor(private mapService: MapService) {
this.mapService.map$.subscribe((map: Map | null) => {
console.log('Map updated in BackgroundLayersService:', map);
this.mapSubject.next(map);
});
}
public map: Map | null;
changeLayer(input: any) {
console.log('test');
console.log(this.map);
}
}
Which loads a "map" from another service, this is the other service:
@Injectable({
providedIn: 'root',
})
export class MapService {
constructor(private store: Store) {
}
@ViewChild('mapId') mapContainer: ElementRef;
private mapSubject = new BehaviorSubject<Map | null>(null);
map$ = this.mapSubject.asObservable();
initializeMap(): void {
this.setMap(
L.map('mapId', {
layers: [],
}).setView([1, 1], 6)
);
}
}
When setMap is called, the first service's constructor console logs the correct value. However when changeLayer is called, the console log shows the value of map to be null.
I don't understand why this is, and I can't seem to pass this map value to other components or services. Would appreciate any help.
Relevant Info: this.map is updated with the correct value before changeLayer is called.
initializeMap sets the map:
initializeMap(): void {
this.setMap(
L.map('mapId', {}
);
}
happens here:
init = () => {
this.mapService.initializeMap();
this.mapService.map$.subscribe((map) => {
this.mapInstance = map;
});
}
and here the value of map from subscribe is also correct, later within the component the value of map is used and is not null.
Solution
So the answer guys, turns out was that the service was a singleton as declared with the following annotation on the service.
@Injectable({
providedIn: 'root',
})
However it wasnt always a singleton, as such there was a provider left over in the standalone component containing this service, meaning that even if the service was a singleton and could be reused, meaning that an extra version was created just for this standalone component.
Thanks for your help!
Answered By - trojaxat
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.