typescript - Angular 4 - Ladda inte om komponenten vid återbesök


I min applikation finns det tre komponenter. 1) Karta 2) Sök 3) Användarprofil

Efter inloggning laddar jag som standard MAP-komponenten och sedan kan jag gå till någon annan skärm via menylänken i sidhuvudet.

Jag vill uppnå funktionalitet så att när jag laddar kartkomponenten i webbläsaren ska den inte ladda om komponenten igen när jag återvänder till kartskärmen från en annan skärm eller med bakåtknappen. För när jag återvänder från en annan skärm laddas alla pushpins och relaterad data om igen och användarens senaste vy på kartan återställs.

Observera - I kartkomponenten laddar jag kartan vid ngOnIt-händelsen.

Hur kan jag uppnå denna funktionalitet i Angular 2/4?

Exempelskärmdump är bifogad för referens.

Svar #1

Så här uppnådde jag detta.

Först - Implementerade RouteReuseStrategy-gränssnittet.

import {RouteReuseStrategy, ActivatedRouteSnapshot, DetachedRouteHandle} from '@angular/router';

export class CustomReuseStrategy implements RouteReuseStrategy {

    handlers: {[key: string]: DetachedRouteHandle} = {};

    shouldDetach(route: ActivatedRouteSnapshot): boolean {
        //console.debug('CustomReuseStrategy:shouldDetach', route);
        return !!route.data && !!(route.data as any).shouldDetach;
    }

    store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
        //console.debug('CustomReuseStrategy:store', route, handle);
        this.handlers[route.routeConfig.path] = handle;
    }

    shouldAttach(route: ActivatedRouteSnapshot): boolean {
        //console.debug('CustomReuseStrategy:shouldAttach', route);
        return !!route.routeConfig && !!this.handlers[route.routeConfig.path];
    }

    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
        //console.debug('CustomReuseStrategy:retrieve', route);
        if (!route.routeConfig) { return null; }
        return this.handlers[route.routeConfig.path];
    }

    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        //console.debug('CustomReuseStrategy:shouldReuseRoute', future, curr);
        return future.routeConfig === curr.routeConfig;
    }

}

Andra - lade till CustomReuseStrategy leverantör i app.module.

import {RouteReuseStrategy} from '@angular/router';
import {CustomReuseStrategy} from './Shared/reuse-strategy';

providers: [
{ provide: RouteReuseStrategy, useClass: CustomReuseStrategy }
]

Tredje - lade till shouldDetach-attribut i app.routing.ts

import { Routes, RouterModule } from "@angular/router";
import { MapComponent } from './components/map/map.component';

const ROUTES: Routes = [
{ path: 'maps', component: MapComponent , canActivate:[AuthGuard], data: { shouldDetach: true} },
];

Relaterade artiklar