ionic 2 undefined不是对象错误

时间:2016-10-25 12:21:29

标签: node.js cordova angular ionic2

我是离子2的新手。我遇到了问题。我使用map定义var map;它正在loadMap()函数内工作。但是,如果我定义像map:any;这样的地图它不起作用。抛出这样的错误。

  

错误:未捕获(在承诺中):TypeError:undefined不是对象   (评估' this.map')

import { Component } from '@angular/core';
import { NavController,Platform } from 'ionic-angular';
import { Geolocation } from 'ionic-native';
import {DataService} from '../../providers/data-service';
declare var L:any;
@Component({
  selector: 'page-my-map',
  templateUrl: 'my-map.html',
  providers:[DataService]
})
export class MyMap {
      public data: any;

map:any=null;
markersLayer;

  myPositionLayer;
  myCircleLayer;
  showingon;
   LeafIconMe;
LeafIcon;


  constructor(platform: Platform, public dataService: DataService) {

      platform.ready().then(() => {

      Geolocation.getCurrentPosition().then((resp) => {
        });

    this.loadMap();
    this.loadData();

    });


  }

  loadMap(){

         this.map = L.map('map', {}).setView([40.980963, 29.0966243], 10);
L.tileLayer(tileURL, {
        maxZoom: 18,
        attribution: ''
    }).addTo(this.map);
     this.map.locate({ setView: true, maxZoom: 16 });


      this.dataService.getData()
        .then(data => {

          this.data = data;
         this.data.forEach(function(veri){
              console.log(veri.lat);
             L.marker([veri.lat, veri.lon]).addTo(this.map);

          })

        });
     console.log("map"+this.map);
  }
loadData(){
               console.log("data"+this.map);




    }


}

我的npm列表如下所示。

npm list --depth=0
msson@ /Users/baris/ionic2/denden/msson
├── @angular/common@2.0.0
├── @angular/compiler@2.0.0
├── @angular/compiler-cli@0.6.2
├── @angular/core@2.0.0
├── @angular/forms@2.0.0
├── @angular/http@2.0.0
├── @angular/platform-browser@2.0.0
├── @angular/platform-browser-dynamic@2.0.0
├── @angular/platform-server@2.0.0
├── @ionic/app-scripts@0.0.36
├── @ionic/storage@1.0.3
├── ionic-angular@2.0.0-rc.1
├── ionic-native@2.2.3
├── ionicons@3.0.0
├── rxjs@5.0.0-beta.12
├── typescript@2.0.3
└── zone.js@0.6.21
你能不能给我任何解决这个问题的建议。提前谢谢..

1 个答案:

答案 0 :(得分:6)

this.data.forEach(function(veri){
    console.log(veri.lat);
    L.marker([veri.lat, veri.lon]).addTo(this.map);
})

您需要使用arrow function(而非function)来保留this上下文

this.data.forEach((veri) => {
    console.log(veri.lat);
    L.marker([veri.lat, veri.lon]).addTo(this.map);
})