0

I need to know a way to keep the current state of my component in Angular when I leave the screen and navigate to another screen.

In my component I have a counter that displays the duration of a service that the user is currently performing, I also have a form with several information about the service that is being performed.

When I exit the screen display and navigate to another screen, the counter can not reset, and the entire screen display should be the same as it was before I left and navigated to another route.

I would also like the state to be maintained when I close the tab and open again and the duration time continues even though I am not having the application open.

The duration should only stop when I click on finalize, I can close the application and open again, the state of the screen with the information will always be maintained and the duration never stops until I end the attendance.

Example.:

Duration before closing application. 00:10:00

10 minutes after closing application and opening again. 00:20:00


How can I do this? Since the life cycle of the components in Angular?

Luiz Ricardo Cardoso
  • 1,554
  • 4
  • 16
  • 37
  • 1
    Possible duplicate of [Maintain state of Search page after navigating back from details page in Angular](https://stackoverflow.com/questions/47935357/maintain-state-of-search-page-after-navigating-back-from-details-page-in-angular) – Heretic Monkey May 27 '19 at 16:09

1 Answers1

1

you need to implement your custom RouteReuseStrategy

app-routing-cache.ts

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

export class AppRoutingCache implements RouteReuseStrategy {
    routesToCache: string[] = ['my-route1']; // add your routes to cache here 
    storedRouteHandles = new Map<string, DetachedRouteHandle>();

    shouldDetach(route: ActivatedRouteSnapshot): boolean {
        return this.routesToCache.indexOf(route.routeConfig.path) > -1;
    }

    store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
        this.storedRouteHandles.set(route.routeConfig.path, handle);
    }

    shouldAttach(route: ActivatedRouteSnapshot): boolean {
        return this.storedRouteHandles.has(route.routeConfig.path);
    }

    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
        return this.storedRouteHandles.get(route.routeConfig.path);
    }

    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        return future.routeConfig === curr.routeConfig;
    }
}

in app.moudle

providers: [
  ...
  { provide: RouteReuseStrategy, useClass: AppRoutingCache }

]
Reza
  • 18,865
  • 13
  • 88
  • 163
  • Okay, this will work while the application is open, and if I close the tab and open it again? I updated the question, added a new expected behavior ... Can you help me with this? – Luiz Ricardo Cardoso May 27 '19 at 16:27