Ionic, почему нативный элемент не определен?

У меня есть ионное приложение, использующее сегменты, и на одном сегменте я хочу отображать карты Google. Когда мы сначала загружаем этот сегмент, он работает, но когда я перехожу к другому сегменту и хочу вернуться к сегменту карт Google, я получаю сообщение об ошибке. И я не знаю, как решить эту проблему.

TypeError: Невозможно прочитать свойство 'nativeElement' неопределенного

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);
}
}

person Kol2gaR    schedule 05.01.2018    source источник


Ответы (2)


вы пытаетесь получить значение из html перед полным рендерингом. создайте тайм-аут внутри ngAfterViewInit, чтобы дождаться рендеринга значений.

const map;
ngAfterViewInit() {
    console.log("afterinit");
    setTimeout(() => {
      console.log(this.mapRef.nativeElement);
      map = new google.maps.Map(this.mapRef.nativeElement,options);
    }, 1000);
  }
person Sachila Ranawaka    schedule 05.01.2018
comment
Вы сэкономили мое время. Спасибо :) - person M Fuat; 14.06.2018

Вы можете использовать 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);
    });
}
person Faly    schedule 05.01.2018