2016-12-01 62 views
1

我一直在通過事件對象訪問變量。 有沒有什麼我可以在這段代碼中重構,因爲我需要在templateUrl中顯示一些註釋,然後在地圖的事件點擊中設置它們。 下面是代碼:Angular2 - 通過事件對象訪問變量

import { Component, OnInit, AfterViewInit } from '@angular/core'; 

    declare var ol: any; 

    @Component({ 
     selector: 'my-map-app', 
     templateUrl: 'app.component.html' 
    }) 
    export class AppComponent implements OnInit, AfterViewInit { 

     static draw: any; 
     annotations: any[]; 

     constructor() { 
      this.annotations = []; 
     } 

     ngOnInit(): void { 

        // ADD MAP 
        AppComponent.map = new ol.Map({ 
         target: 'map', 
         layers: layers, 
         view: new ol.View({ 
          center: ol.proj.fromLonLat([10, 10]), 
          zoom: 2 
         }) 
        }); 

        // Action when clicking on a Point (no edition mode) 
        AppComponent.map.on('singleclick', function(evt) { 
         // here I want to access and set the array of annotations 
         //this.annotations or AppComponent.annotations is not available 

        }); 
    } 

編輯:上app.component.html:

<select > 
    <option *ngFor="let annotation of annotations">{{annotation.name}}</option> 
</select> 

回答

1

我用做下面這個特定的問題,但如果有確切的解決方法是可用的PLZ讓我知道

    ngOnInit(): void { 
        let _self:any = this; 
        AppComponent.map = new ol.Map({ 
         target: 'map', 
         layers: layers, 
         view: new ol.View({ 
          center: ol.proj.fromLonLat([10, 10]), 
          zoom: 2 
         }) 
        }); 

        // Action when clicking on a Point (no edition mode) 
        AppComponent.map.on('singleclick', function(evt) { 
         console.log("this = ",_self); 


        }); 
    } 
+0

我更新了我的問題 - 因爲我可以記錄正確設置在我的事件中的_self對象 - 但是如果我在那裏更新它(並且我需要它):視圖仍然不是。有沒有辦法做到這一點? – F3L1X79

+0

好吧,最後奇怪的是,視圖有時*更新,有時不是 - 當不是時,我需要更改我的選擇值以查看已更新的列表。如果有任何線索,我將不勝感激。 – F3L1X79

0

最後掙扎了一整天之後,這裏就是我不得不添加(ChangeDetectorRef):

import { Component, OnInit, AfterViewInit, ChangeDetectorRef } from '@angular/core'; 

    declare var ol: any; 

    @Component({ 
     selector: 'my-map-app', 
     templateUrl: 'app.component.html' 
    }) 
    export class AppComponent implements OnInit, AfterViewInit { 

     static draw: any; 
     static reload: any; 
     annotations: any[]; 

     constructor(private changeDetectorRef: ChangeDetectorRef) { 
      AppComponent.reload = changeDetectorRef; 
      this.annotations = []; 
     } 

     ngOnInit(): void { 
        let _self: any = this; //from @anshuVersatile 

        // ADD MAP 
        AppComponent.map = new ol.Map({ 
         target: 'map', 
         layers: layers, 
         view: new ol.View({ 
          center: ol.proj.fromLonLat([10, 10]), 
          zoom: 2 
         }) 
        }); 

        AppComponent.map.on('singleclick', function(evt) { 
         self.annotations = ['foo', 'bar']; 
         AppComponent.reload.detectChanges(); //this is what i had to trigger 
        }); 
    } 

感謝@anshuVersatile - 如果有人找到更好的東西,請告訴我們!