Ionic 为什么 nativeElement 是 undefined 的?

Ionic why nativeElement of undefined?

我有一个使用分段的离子应用程序,我想在一个分段上显示 google 地图。当我们首先加载该段时它可以工作,但是当我转到另一个段并且我想返回到 google 地图段时,我收到一条错误消息。而且我不知道如何解决这个问题。

TypeError: Cannot read property 'nativeElement' of undefined

HTML

<ion-header>
    <ion-toolbar>
      <ion-segment [(ngModel)]="gps" color="light">
        <ion-segment-button value="information" (click)="onInformationClick()">
          <ion-icon name="information-circle"></ion-icon>
        </ion-segment-button>
        <ion-segment-button value="navigate" (click)="onNavigateClick()">
          <ion-icon name="navigate"></ion-icon>
        </ion-segment-button>
        <ion-segment-button value="settings" (click)="onSettingsClick()">
            <ion-icon name="settings"></ion-icon>
          </ion-segment-button>
      </ion-segment>
    </ion-toolbar>
  </ion-header>


<ion-content class="home">
        <div [ngSwitch]="gps" id="contenu">
            <div *ngSwitchCase="'information'"><h1>information</h1></div>


            <div #map id="map" *ngSwitchCase="'navigate'"></div>


            <div *ngSwitchCase="'settings'"><h1>settings</h1></div>
        </div>

</ion-content>

TypeScript

import { Component ,ViewChild, ElementRef} from '@angular/core';
import { NavController, Platform} from 'ionic-angular';
import { AndroidPermissions } from '@ionic-native/android-permissions';

declare var SMS:any;
declare var google:any;
@Component({
  selector: 'page-informations',
  templateUrl: 'informations.html'
})
export class InformationsPage {
  //mySMS:any[]=[];
  gps: string = "navigate";
  @ViewChild('map') mapRef:ElementRef;

  constructor(
    public navCtrl: NavController, 
    public androidPermissions: AndroidPermissions, 
    public platform:Platform) 
  {
// constructor 
}
  public onNavigateClick(){
    this.gps = "navigate";
    this.DisplayMap(); 
  }
  public onInformationClick(){
    this.gps = "information";
  }

  public onSettingsClick(){
    this.gps = "settings";
  }
 //Lance l'affichage de la map'

//Définition des paramètre de la map
 DisplayMap() { 
  //Coordonnée de la zone de départ
  const location = new google.maps.LatLng(49.898738,
    1.131385);

  // Options sur la coordonnée de départ
  const options = {
    center:location,
    zoom:19,
    streetViewControl:false,
    mapTypeId:'hybrid'
  };

  // Coordonnées pour chaque points de gps récupéré
  const coordinates =[
    {lat: 80.898613, lng: 1.131438},
    {lat: 80.898501, lng: 1.131355},
    {lat:80.898698, lng: 1.130996},
    {lat: 80.898822, lng: 1.131206}
  ];

  //Option des points de coordonnée gps récupéré
  const flightPath = new google.maps.Polyline({
    path: coordinates,
    geodesic: true,
    strokeColor: '#FBE625',
    strokeOpacity: 1.0,
    strokeWeight: 2
  });

  //Déclaration de la map
  const map = new google.maps.Map(this.mapRef.nativeElement,options);

  //Ajout des points de coordonnées gps récupéré, sur la map
  flightPath.setMap(map);
}
}

您正试图在完全渲染之前从 html 获取值。在 ngAfterViewInit 内创建一个超时以等待值被呈现。

const map;
ngAfterViewInit() {
    console.log("afterinit");
    setTimeout(() => {
      console.log(this.mapRef.nativeElement);
      map = new google.maps.Map(this.mapRef.nativeElement,options);
    }, 1000);
  }

您可以使用 Subject 来检测 mapRef 是否未定义:

@ViewChild('map') mapRef:ElementRef;
private afterViewInitSubject: Subject<any> = new Subject();

ngAfterViewInit() {
    this.afterViewInitSubject.next(true);
}

DisplayMap() {

    if (this.mapRef) {
        /* ... */
        this.map = new google.maps.Map(this.mapRef.nativeElement,options);
    } else {
        this.afterViewInitSubject.subscribe(() => {
        /* ... */
        this.map = new google.maps.Map(this.mapRef.nativeElement,options);
    });
}