2016-12-01 56 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 - 如果有人找到更好的东西,请告诉我们!