The*_*orm 1 leaflet ngx-leaflet angular5
我在尝试将 onEachFeature Methode 用于 geoJSON 层时遇到问题。我尝试为每个功能分配一个点击侦听器。问题是,当我单击某个功能时,总是会收到该错误:
未捕获的类型错误:无法读取未定义的属性“detectChanges”
我可以想到这是因为在构造函数运行之前分配了层,但是在 ngOnInit 函数中这样做也不起作用。如果有一个很好的方法来做到这一点会很酷:)
constructor(private changeDetector: ChangeDetectorRef){}
fitBounds: LatLngBounds;
geoLayer = geoJSON(statesData, {onEachFeature : this.onEachFeature});
onEachFeature(feature , layer) {
layer.on('click', <LeafletMouseEvent> (e) => {
this.fitBounds = [
[0.712, -74.227],
[0.774, -74.125]
];
this.changeDetector.detectChanges();
});
}Run Code Online (Sandbox Code Playgroud)
layer: Layer[] = [];
fitBounds: LatLngBounds;
onEachFeature(feature , layer : geoJSON) {
layer.on('click', <LeafletMouseEvent> (e) => {
console.log("tets"+e.target.getBounds().toBBoxString());
this.fitBounds = [
[0.712, -74.227],
[0.774, -74.125]
];
this.changeDetector.detectChanges();
});
}
constructor(private changeDetector: ChangeDetectorRef){}
ngOnInit() {
let geoLayer = geoJSON(statesData, {onEachFeature : this.onEachFeature});
this.layer.push(geoLayer);
}Run Code Online (Sandbox Code Playgroud)
您需要确保this在您的回调中可以访问该权限。您可以function.bind()在 Javascript 中使用。请参阅:https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
constructor(private changeDetector: ChangeDetectorRef){}
fitBounds: LatLngBounds;
geoLayer = geoJSON(statesData, {
// Need to bind the proper this context
onEachFeature : this.onEachFeature.bind(this)
});
onEachFeature(feature , layer) {
// 'this' will now refer to your component's context
let that = this;
layer.on('click', <LeafletMouseEvent> (e) => {
that.fitBounds = [
[0.712, -74.227],
[0.774, -74.125]
];
// Aliased 'that' to refer to 'this' so it is in scope
that.changeDetector.detectChanges();
});
}
Run Code Online (Sandbox Code Playgroud)
该let that = this诀窍是确保你没有对同一问题click的事件处理程序。但是,您也可以使该处理程序成为您的类中的一个函数,并使用 bind 来设置this。
| 归档时间: |
|
| 查看次数: |
990 次 |
| 最近记录: |