更改路线时重新实例化 Angular2 服务

Angular2 Service reinstantiated when changing route

我有一个异步加载 gmaps api 的服务。当我加载它时,我在该服务中保存了一个 属性 名称 "isGoogleMapLibraryLoaded" 设置为 true。

当我转到另一条路线(当然没有刷新)并返回到之前的路线时,服务重新实例化并且我丢失了 "isGoogleMapLibraryLoaded" 属性.

如何在路由之间切换时持续存在的服务中设置属性?

我的服务:

import { Injectable } from '@angular/core';

const GOOGLE_MAPS_API_KEY = 'AIzaSyDvo543530SU_xsZLvZ6SjTFbt1FPW9FI';
const URL = `https://maps.googleapis.com/maps/api/js?key=${GOOGLE_MAPS_API_KEY}&callback=__onGoogleMapLoaded`;

@Injectable()
export class GoogleMapService {
  /**
   * Google maps loading status (althought loading is not completed)
   */
  private isGoogleMapLibraryLoaded: Boolean = false;
  constructor(){
  }

  getNewMapInstance(element, props){
    console.log(this.isGoogleMapLibraryLoaded);
    this._loading().then(() => {
      return new google.maps.Map(element, props);
    });
  }

  private _loading(){
    return new Promise((resolve, reject) => {
      if(!this.isGoogleMapLibraryLoaded){
        this.isGoogleMapLibraryLoaded = true;

          resolve();

      }else{
        resolve();
      }
    });
  }
}

我在 bootstrap 中添加了服务,并将其注入到组件构造函数中

构造函数(私有地图服务:GoogleMapService){}

ngAfterViewInit() {
    this.googleMapInstance = this.mapService.getNewMapInstance(this.googleMapWrapperElement.nativeElement, {
      center: {lat: -34.397, lng: 150.644},
      scrollwheel: false,
      zoom: 8
    });
  }

这取决于您在哪里提供服务。如果您在根组件中提供它,则该实例将与根组件存在的时间一样长(只要您的 Angular 应用程序是 运行)。

如果你在你的路由组件中提供它,它会在组件被移除后立即被丢弃。