使用 angular 加载一次 mapbox

Load mapbox once with angular

我目前正在设计一个在两个不同页面上使用相同地图框地图的应用程序。当我导航到每个页面时,地图每次都会重新加载。目前这是一个相当大的问题,因为地图需要很长时间才能加载,因为我在上面显示了大量的热图数据。

有没有办法确保在两个页面之间导航时地图保持加载状态?

我已经开始探索状态管理,但我不确定这是否是解决问题的方法,而且我仍然不确定它能完成什么。

您应该使用 RouteReuseStrategy,如此处所述:https://itnext.io/cache-components-with-angular-routereusestrategy-3e4c8b174d5f

创建服务缓存-路由-reuse.strategy.ts:

import { RouteReuseStrategy } from '@angular/router/';
import { ActivatedRouteSnapshot, DetachedRouteHandle } from '@angular/router';
export class CacheRouteReuseStrategy implements RouteReuseStrategy {
    storedRouteHandles = new Map<string, DetachedRouteHandle>();

    allowRetrieveCache = {
        'mapbox': true
    };

    shouldReuseRoute(before: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {

        if (this.getPath(before) === 'the-path-of-the-first-component' && this.getPath(curr) === 'the-path-of-the-second-component') {
            this.allowRetrieveCache['mapbox'] = true;
        } else {
            this.allowRetrieveCache['mapbox'] = false;
        }

        return before.routeConfig === curr.routeConfig;
    }

    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null {
        return this.storedRouteHandles.get(this.getPath(route)) as DetachedRouteHandle;
    }

    shouldAttach(route: ActivatedRouteSnapshot): boolean {
        const path = this.getPath(route);
        if (this.allowRetrieveCache[path]) {
            return this.storedRouteHandles.has(this.getPath(route));
        }

        return false;
    }

    shouldDetach(route: ActivatedRouteSnapshot): boolean {
        const path = this.getPath(route);
        if (this.allowRetrieveCache.hasOwnProperty(path)) {
            return true;
        }

        return false;
    }

    store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void {
        this.storedRouteHandles.set(this.getPath(route), detachedTree);
    }

    private getPath(route: ActivatedRouteSnapshot): string {
        if (route.routeConfig !== null && route.routeConfig.path !== null) {
            return route.routeConfig.path;
        }

        return '';
    }
}

然后在你的app.module.ts中注册:

...
providers: [{
  provide: RouteReuseStrategy,
  useClass: CacheRouteReuseStrategy
}],
...

您可能想要调整 shouldReuseRoute 方法的行为(例如,我相信它在从 map1 导航到 map2 时有效,但相反)。