Javascript 无法在回调函数中获取angular 2作用域
我需要更新回调函数内的数组对象,我使用了以下几行,但这些值在回调循环的范围内设置,而不是作为角度变量,因此我的视图不会更新。如果在回调函数内打印,则deviceval值会更改,但在回调函数外,该值仍然是旧值Javascript 无法在回调函数中获取angular 2作用域,javascript,performance,angular,angularjs-directive,angularjs-scope,Javascript,Performance,Angular,Angularjs Directive,Angularjs Scope,我需要更新回调函数内的数组对象,我使用了以下几行,但这些值在回调循环的范围内设置,而不是作为角度变量,因此我的视图不会更新。如果在回调函数内打印,则deviceval值会更改,但在回调函数外,该值仍然是旧值 export class DashboardComponent implements OnInit { hideTable: boolean = true; public deviceVal:any; constructor(private ref: ChangeDetecto
export class DashboardComponent implements OnInit {
hideTable: boolean = true;
public deviceVal:any;
constructor(private ref: ChangeDetectorRef) {}
ngOnInit() {
this.deviceVal = deviceData;
console.log(this.deviceVal);
var container = $('.map-canvas');
var options = {
center: new google.maps.LatLng(41.676258, -99.683199),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
gmap = new google.maps.Map(container[0], options);
this.drawChart(deviceData);
this.plotMarkers();
}
plotMarkers(){
$.each(deviceData, function(key, val) {
var controller=this;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(parseInt(val.lat), parseInt(val.lon)),
map: gmap,
});
google.maps.event.addListener(marker, 'click', function() {
this.deviceVal = val;
});
markerCache.push(marker);
})
}
}
问题在于:
$.each(deviceData, function(key, val) {
var controller=this;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(parseInt(val.lat), parseInt(val.lon)),
map: gmap,
});
google.maps.event.addListener(marker, 'click', function() {
this.deviceVal = val;
});
markerCache.push(marker);
})
将函数用作回调函数时,“this”值会更改。你最好在这里读一下
您可以使用箭头功能修复此问题:
plotMarkers(){
$.each(deviceData, (key, val) => {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(parseInt(val.lat), parseInt(val.lon)),
map: gmap,
});
google.maps.event.addListener(marker, 'click', () => {
this.deviceVal = val;
});
})
}
但是你还有很多其他的问题,比如:老实说,你不需要使用jQuery,你应该避免在ng2应用程序中使用jQuery,“gmap”变量没有定义,你可以将它设置为类的一个属性,就像你对“deviceVal”所做的那样,例如,“markerCache”也没有定义,没有drawChart方法,“deviceData”未在plotMarkers中定义。我在导出组件之前声明了一个全局变量,如
var controller;
并在ngoninit中初始化它
controller = this;
并将控制器传递给addlistener
google.maps.event.addListener(marker, 'click', () => {
controller.deviceVal=[];
controller.deviceVal.push(val);
//console.log(controller.deviceVal+"end....................................")
});
我认为您应该使用$scope.$apply,无论您在哪里使用非角度回调来告诉angular运行更改检测循环。我不认为这是唯一的问题,您的指针也不正确。您正在回调中指定类的this引用。我想你是想把它放在回调上面,这样它就指向了正确的方向。deviceVal@AbdelAngular 2Correct中没有$scope,这将确保他的指针引用的是他想要引用的对象。这是一个类。嗨,christian,我在导出类之前声明了gmap,markercache全局,我刚刚上传了我代码中有问题的部分。如果没有提到绘图图,我已经使用箭头函数更改了函数,但视图仍然没有刷新