-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....................................") 
          });