BingMap - getting prototype of null error

后端 未结 4 426
无人共我
无人共我 2021-01-15 14:24

I have searched google and stackoverflow, but could not find a solution for this issue. I am loading the map like this, in my vi

4条回答
  •  臣服心动
    2021-01-15 15:13

    Issue solved for me after wrapping the "loadMap" method with a "setTimeout":

    HTML

    Component

    import {Component, OnDestroy, OnInit, ViewChild} from '@angular/core';
    import {BingMapService} from './bing-map.service';
    import {Subscription} from "rxjs";
    
    @Component({
      moduleId: module.id,
      selector: 'bing-map',
      styleUrls: ['./bing-map.component.css'],
      templateUrl: './bing-map.component.html'
    })
    export class BingMapComponent implements OnInit, OnDestroy {
      @ViewChild('bingMap') bingMap: any;
      serviceSubject: Subscription;
    
      constructor(
        private bingMapService: BingMapService
      ) {}
    
      loadMap() {
        const map = new Microsoft.Maps.Map(this.bingMap.nativeElement, {});
      }
    
      ngOnInit() {
        this.serviceSubject = this.bingMapService.injectionSubject().subscribe((loaded) => {
          if (loaded) {
            window.setTimeout(() => {
              this.loadMap();
            });
          }
        });
    
        this.bingMapService.injectBingMapMainScript();
      }
    
      ngOnDestroy() {
        if (this.serviceSubject) {
          this.serviceSubject.unsubscribe();
        }
      }
    }
    

    Service

    import {Observable, Subject} from 'rxjs';
    import {Injectable} from '@angular/core';
    import {Http} from '@angular/http';
    
    @Injectable({
      providedIn: 'root'
    })
    export class BingMapService {
      private subject = new Subject();
    
      constructor(
        private http: Http,
      ) {}
    
      injectBingMapMainScript() {
        let script = document.createElement('script');
        script.src = 'https://www.bing.com/api/maps/mapcontrol?key=[YourKey]';
        script.async = true;
    
        document.body.appendChild(script);
    
        script.onload = () => {
          this.subject.next(true);
        };
      }
    
      injectionSubject(): Observable {
        return this.subject.asObservable();
      }
    }
    

提交回复
热议问题