Angular 角度7为什么我的var在所有函数中都不相等
我有一个大问题,我相信我已经做到了,而且效果非常好 这是我的密码:Angular 角度7为什么我的var在所有函数中都不相等,angular,variables,scope,Angular,Variables,Scope,我有一个大问题,我相信我已经做到了,而且效果非常好 这是我的密码: import { Component, OnInit } from '@angular/core'; import { Map, latLng, tileLayer, Layer, marker, icon, Icon } from 'leaflet'; @Component({ selector: 'app-map', templateUrl: './map.component.html', styleUrls:
import { Component, OnInit } from '@angular/core';
import { Map, latLng, tileLayer, Layer, marker, icon, Icon } from 'leaflet';
@Component({
selector: 'app-map',
templateUrl: './map.component.html',
styleUrls: ['./map.component.scss']
})
export class MapComponent implements OnInit {
public m : Map;
public n : number = 3;
public markerIcon : Icon = icon({
iconUrl: 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.2.0/images/marker-icon.png'
});
constructor() { }
ngOnInit() {
this.initMap();
}
initMap(){
console.log(this.n);
//this.m = L.map('map').setView([44.8333, -0.5667], 5);
this.m = new Map('map').setView([44.8333, -0.5667], 5);
tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(this.m);
this.m.on('click', this.addDestination);
console.log(this.m);
}
addDestination(){
console.log(this.m);
}
}
“initMap”中的第一个console.log返回映射的实例,但addDestination中的第二个console.log返回未定义的实例
我做了10000000次测试。花了太多的时间,请帮帮我 在您的
initMap
方法中:
改变这个
this.m.on('click',this.addDestination');
致:
this.m.on('click',this.addDestination.bind(this));
问题是,当您将方法作为回调传递时,this
的上下文是不同的
阅读有关MDN的更多信息使用箭头功能。而不是
addDestination(){
console.log(this.m);
}
做
您还可以使用arrow函数来解决此问题,而不是在
addDestination()
方法上使用.bind()
initMap(){
console.log(this.n);
//this.m = L.map('map').setView([44.8333, -0.5667], 5);
this.m = new L.Map('map').setView([44.8333, -0.5667], 5);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(this.m);
this.m.on('click', this.addDestination);
console.log(this.m);
}
addDestination=()=>{
console.log(this.m);
}
工作演示:与
此
的上下文相关的问题。尝试使用箭头函数addDestination=()=>console.log(this.m)你能做一个stackblitz这样我们就可以调试它吗?这能回答你的问题吗?非常感谢。我确信这是一个上下文/范围问题,非常感谢!
initMap(){
console.log(this.n);
//this.m = L.map('map').setView([44.8333, -0.5667], 5);
this.m = new L.Map('map').setView([44.8333, -0.5667], 5);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(this.m);
this.m.on('click', this.addDestination);
console.log(this.m);
}
addDestination=()=>{
console.log(this.m);
}