IONIC 3: 无法读取未定义的 'nativeElement' 属性 TypeError: 无法读取未定义的 'nativeElement' 属性。

4
我正在学习IONIC 3,并且现在正在使用Google Maps API开发应用程序。问题是,当我尝试执行我的应用程序时,启动后出现以下消息: inicio.html
Error: Uncaught (in promise): TypeError: Cannot read property 
'nativeElement' of undefined
TypeError: Cannot read property 'nativeElement' of undefined

这是导致问题的代码片段:

inicio.ts(仅代码的一部分)

loadMap(){

this.geolocation.getCurrentPosition().then((position)=>{

  let latLng = new google.maps.LatLng(position.coords.latitude,
                                      position.coords.longitude);

  let mapOptions = {
    center: latLng,
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }

  this.map = new google.maps.Map(this.mapElement.nativeElement, 
  mapOptions);

  }, (err) => {
  console.log(err);
  });

}

inicio.ts(完整代码)

import { Component,ViewChild, ElementRef } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Geolocation } from '@ionic-native/geolocation';
import { Platform } from 'ionic-angular';

declare var google: any;

/**
* Generated class for the InicioPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more 
info on
* Ionic pages and navigation.
*/

@IonicPage()
@Component({
selector: 'page-inicio',
templateUrl: 'inicio.html',
})
export class InicioPage {

@ViewChild('map') mapElement: ElementRef;
map: any; //Google map manager.
coords : any = { lat:0, lng: 0 } 

constructor(
public navCtrl: NavController, 
public navParams: NavParams,
public platform: Platform,
public geolocation: Geolocation) {

  platform.ready().then(() => {
      //Platform ready. All plugins enabled.
  });
}

ionViewDidLoad() {
console.log('ionViewDidLoad InicioPage');
this.loadMap();
}

loadMap(){

this.geolocation.getCurrentPosition().then((position)=>{

  let latLng = new google.maps.LatLng(position.coords.latitude,
                                      position.coords.longitude);

  let mapOptions = {
    center: latLng,
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }

this.map = new google.maps.Map(this.mapElement.nativeElement, 
mapOptions);

}, (err) => {
  console.log(err);
});

}
}

inicio.html

<!--
Generated template for the InicioPage page.

See http://ionicframework.com/docs/components/#navigation for more 
info on
Ionic pages and navigation.
-->
<ion-header>

<ion-navbar>
<ion-title>Inicio</ion-title>
</ion-navbar>

</ion-header>


<ion-content padding>
<!--<h1> Esta es la página de inicio, aquí situaremos un mapa con un 
boton de añadir lugar.</h1>-->
<div id="map"></div>

</ion-content>

inicio.scss

page-inicio {

ion-content{
    .scroll{
        height: 100%;   
    }
    #map{
        width: 100%;
        height: 100%;
    }
}

}

感谢您的帮助!

1
听起来像是DI错误,请您在问题中添加类构造函数好吗?此外,请添加 mapElement 属性的声明和初始化。 - Aluan Haddad
1
完成!已添加完整代码。 - Daniel Jose Carrillo Herrera
我认为你需要将代码移动到类似于 ngAfterViewInit 的位置,因为 @ViewChild('map') 可能在 ionViewDidLoad 生命周期钩子中还不可用。虽然我不记得要使用哪个钩子。 - Aluan Haddad
我在ngAfterViewInit中调用了loadMap(),但仍然无法工作。 :( - Daniel Jose Carrillo Herrera
你的模板中是否含有像 <div #map> 这样的标签? - Aluan Haddad
显示剩余4条评论
2个回答

6
在你的 HTML 中,你需要改变:

<div id="map"></div>

to

<div #map id="map"></div>

然后 @ViewChild('map') mapElement: ElementRef; 将会正确地被解析。

更多详情请参见这里


请修改您的答案,并添加一些关于解决方案背景的描述,以及指向离线资源的简要说明。还请参见[答案]。 - compor
刚刚发生了同样的事情。我从HTML中删除了#map,然后开始想知道为什么会出现这个错误。@Daniel,你是在跟随Josh Morony的教程吗?https://www.joshmorony.com/ionic-2-how-to-use-google-maps-geolocation-video-tutorial/ - Ryan Coolwebs
如果有人对elementRef的解析不熟悉,这是来自Angular核心部分的:import { ElementRef } from '@angular/core'; - Grant

1
这篇文章有点晚了,但对于那些在按照这里的Josh教程后仍然遇到错误的人来说,我通过将loadMap()函数调用放在ionViewDidLoad()而不是constructor()中解决了我的错误。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接