-1

我需要更新回调函数内部的阵列对象,我使用的下面的行,但这些值是以回叫环不是作为角度变量,这样的范围设定我(deviceval)如果我在回调中打印它的值,它的值会发生变化,但是在值之外仍然是旧的。没能获得角度2范围内回叫功能

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); 
    }) 
    } 
} 
+0

我想你应该使用'$ scope。$ apply()'无论你使用的是非角度回调来告诉角度运行一个变化检测cy CLE。 – Abdel

+0

我不认为这是唯一的问题,你的指针也是不正确的。你正在分配回调中的this参考(类的)。我想你的意思是把回调以上,使其指向正确的'''this.deviceVal''' – Abdel

+0

@Abdel存在角2 –

回答

1

的问题是在这里:

$.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); 
}) 
当您使用()的函数作为回调函数

,在 '这个' 值被改变。你最好在这里读一下这个。

可以解决这个问题则使用箭头功能:

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(说实话,你应该避免的jQuery在NG2 appmap),'gmap'变量没有被定义(你可以将它设置为类的属性,例如你已经对'deviceVal'进行了设置),'markerCache'没有被定义,没有drawChart方法,'' deviceData'在plotMarkers()中没有定义。

+0

正确的,这将确保没有$范围他的指针引用的东西,他希望以供参考。这是班级。 – Abdel

+0

喜基督徒,我已经宣布GMAP,markercache出口类全球前和我刚刚上传我的code.where的问题的一部分drawchart没有提到 – nandhini

+0

我一直使用箭头功能仍然认为不会刷新更改的功能 – nandhini

0

我解决它由类似

var controller; 

出口组件之前定义一个局部变量和在ngoninit()初始化它,

controller = this; 

并通过控制器的addListener,

google.maps.event.addListener(marker, 'click',() => { 
          controller.deviceVal=[]; 
          controller.deviceVal.push(val); 
          //console.log(controller.deviceVal+"end....................................") 
          });