我有两个组件: map.component 和 choose-coordinates.component 。他们都是兄弟姐妹,都在components文件夹中。我还有一个服务,可以在组件之间进行通信。
在ngOnInit方法的 choose-coordinates.ts 中,我从表单中获取坐标,并使用服务将该坐标发送到组件图。
choose-coordinates.component.ts
ngOnInit() {
const cords: Array<number> = [this.pointForm.get('X_WGS84').value, this.pointForm.get('Y_WGS84').value];
this.mapService.setChangeCords(cords);
}
map.service.ts
getChangeCords(): Observable<Array<number>> {
return this.changeCords.asObservable();
}
setChangeCords(cords) {
this.changeCords.next(cords);
}
在 map.component.ts 中,我将拾取此坐标并在元素 map 上调用方法 setView 。 em>。
map.component.ts
this.mapService.getChangeCords().subscribe((cords: Array<number>) => {
this.map.setView(latLng([cords[0], cords[1]]), 19);
});
但是在我想调用方法setView()
,this.map === undefined
的那一刻,所以我无法调用方法setView()
。
ERROR TypeError:无法读取未定义的属性'setView'
变量this.map
用onMapReady()
方法初始化:
onMapReady(map: Map) {
this.map = map;
}
此方法在map.component.html中(我使用ngx-leaflet)
<div
leaflet
[leafletLayers]="layers"
(leafletMapReady)="onMapReady($event)"
[leafletOptions]="options">
</div>
我想知道在创建变量this.map之前是否可以停止订阅。我想像这样的东西:
this.mapService.getChangeCords().subscribe((cords: Array<number>) => {
if(this.map !== undefined){
this.map.setView(latLng([cords[0], cords[1]]), 19);
}
});
或者也许可以将组件 choose-coordinates.component 初始化为最后一个组件-在 map.component 之后。
因为我希望在调用方法setView()
之前定义this.map元素。