Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
667 views
in Technique[技术] by (71.8m points)

angular - Getting Error: Uncaught (in promise): TypeError: Cannot read property 'value' of null when I implement ngAfterViewInit

I'm trying to show a Google Map which gets the place_id from an html value.

activity-details.page.html

                    <ion-col>
                        <div id="map"></div>
                        <div *ngIf="activities">
                        <input type="hidden" id="place_id" value="{{ activities.place_id }}" />
                        </div>
                    </ion-col>
                </ion-row>

This is the code returned in the browser.

<input _ngcontent-irr-c150="" type="hidden" id="place_id" value="ChIJ21P2rgUrTI8Ris1fYjy3Ms4">

I'm trying to set the map options as the last thing after all the code has loaded.

activity-details.page.ts

    ngAfterViewInit() {
    this.geocodePlaceId(
      this.geocoder = new google.maps.Geocoder(),
      this.map = new google.maps.Map(
        document.getElementById("map") as HTMLElement,
        {
          zoom: 8,
        }
      ),
      this.infowindow = new google.maps.InfoWindow());
  }

The issue starts when get I the place_id value from the HTML in this last function.

activity-details.page.ts

geocodePlaceId(
    geocoder: google.maps.Geocoder,
    map: google.maps.Map,
    infowindow: google.maps.InfoWindow
  ) {
    const placeId = (document.getElementById("place_id") as HTMLInputElement).value;
    geocoder.geocode({ placeId: placeId }, (results, status) => {
      ...//the rest of the options set up for the map
  }

I keep getting. ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'value' of null TypeError: Cannot read property 'value' of null

What am I doing wrong?

question from:https://stackoverflow.com/questions/65874332/getting-error-uncaught-in-promise-typeerror-cannot-read-property-value-of

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Add an if condition so that you want have to worry about errors

geocodePlaceId(
    geocoder: google.maps.Geocoder,
    map: google.maps.Map,
    infowindow: google.maps.InfoWindow
  ) {
    const placeId = (document.getElementById("place_id") as HTMLInputElement).value;
    if (placeId) {
        geocoder.geocode({ placeId: placeId }, (results, status) => {
            ...//the rest of the options set up for the map
        }
    }

   // So whats happening is, placeId is not getting a value and even before you get it, you are setting it in the geocoder.geocode line. Wait for the value to come and then set it. 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...