3

I would like to keep web page in memory so that when I click on back button (not the one on web browser) or on a routerlink, the HTML page instantly loads if I already visit it(because I have some data to load that I don't want to be reload).

I've seen a method with tabbed interface : https://www.w3.org/Style/Examples/007/target.en.html#tab1 but it is not adapted for my code architecture.

I'm using routerlinkin angular2 to navigate threw pages and a back button calling a function on click to go to the previous page.

I try to detail as far as I can so people can understand better my code architecture and the way routerlink method works.

Back button function (works independently from routerlink) :

 goBack() {
 window.history.back();
 }

The router link method from page 1 to page 2:

page1.html :

<a[routerLink]="['PAGE2']"> go to page 2</a>

page1.ts component:

 import { Router, ROUTER_DIRECTIVES } from '@angular/router-deprecated';
 @Component({
 selector: 'page1',
 templateUrl: 'page1.html',
 styleUrls:  ['page1.css'],
 directives: [ROUTER_DIRECTIVES]
 })

main.ts :

import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '@angular/router-deprecated';

@Component({
providers: [ROUTER_PROVIDERS]
})

@RouteConfig([
{ path: '/page2',  name: 'PAGE2',  component: Page2}]) //component representing class Page2 in page2.ts

Any idea to help me manage it is welcomed, thanks by advance !

slidefizz
  • 257
  • 5
  • 12

2 Answers2

2

Just cache the data in the service like explained in What is the correct way to share the result of an Angular 2 Http network call in RxJs 5?

There is currently no way to prevent the router from re-creating the component when you route away and back to the component.

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
1

Well, for those having the same problem, I think the best way to manage it is to map the data into a localStorage key like this :

  localStorage.setItem('favoris',JSON.stringify(my_array)); //set my data array
  array =  JSON.parse(localStorage.getItem('key_name')); //get in array

And then ngOnInitin the class called by the router will call the initial function depending of localStorage key being true or not.

slidefizz
  • 257
  • 5
  • 12