I am still new to angular. I was working on a feature where the user selects data in a certain part of the page and then clicks a button which redirects them to another page with the data selected. Now I am trying to make a go back button which returns you to the previous page how it was before I routed to the next page with all the data and selected data that was previously there.
When I look around most people are saying use one of these methods
goBack(){
window.history.back();
}
goBack(){
window.history.back();
}
goBack(){
this.router.navigate(['path'])
}
however when I do this it reverts me back to the previous page without any of the data like a clean refresh.
Is there an easy way to go back to the previous page like how it was before I routed to a new place.
Thank you I really appreciate any help I am on angular version 13.2.3
CodePudding user response:
You have several options,considering that writing a service class could be a bit cumbersome i would suggest to use the local storage approach (#2), not less important this approaches are history agnostic:
1-Create a shared service
@Injectable({
providedIn: 'root',
})
export class CustomService {
data = '';
}
export class OneComponent implements OnInit {
constructor(private myService: CustomService){};
ngOnInit(): void {
this.myService.data = "Some text data stored"
}
}
2-Use local storage
The purpose of LocalStorage is saving information on the client side and then we could use this information somewhere in project.
Code extract:
Instead of using LocalStorage directly in our Angular project create a wrapper class.
.
.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class InfoService {
constructor() { }
public get name(){
return localStorage.getItem('name');
}
public set name(value:string){
localStorage.setItem('name', value);
}
.
.
Right now we have only one place which we will change. This class is much more easier to extend than add a new line of LocalStorage.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class InfoService {
constructor() { }
public get name(){
return localStorage.getItem('name');
}
public set name(value:string){
localStorage.setItem('name', value);
}
public get user(): User{
return JSON.parse(localStorage.getItem('user'));
}
public set user(value: User){
localStorage.setItem('user', JSON.stringify(value));
}
}
export class User {
public name: string = '';
public surname: string = '';
}
Combination of Service and LocalStorage has benefits. Service class is easy to extend and change, that is save a lot of precise time.
Full source: source
CodePudding user response:
With you requirement, ReuseRoutingStrategy
will suited with this stackblitz
The origin component won't be destroy while you routed to other route.
which mean, everything still be there even value in form input and also ngOnDestroy
won't active as well.
How to
Modify provider of
RouteReuseStrategy
in app.module.tsproviders: [{ provide: RouteReuseStrategy, useClass: ReuseRoutingStrategy }]
Implement
ReuseRoutingStrategy
export class ReuseRoutingStrategy implements RouteReuseStrategy { storedHandles: { [key: string]: DetachedRouteHandle } = {}; shouldDetach(route: ActivatedRouteSnapshot): boolean { return route.data.reuseRoute || false; } store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void { if (route.data.reuseRoute) { this.storedHandles[route.data.reuseKey] = handle; } } shouldAttach(route: ActivatedRouteSnapshot): boolean { const handle = this.storedHandles[route.data.reuseKey]; return !!route.routeConfig && !!handle; } retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle { const id = route.data.reuseKey; if (!route.routeConfig || !this.storedHandles[id]) { return null; } return this.storedHandles[id]; } shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean { return future.routeConfig === curr.routeConfig; } }
Add
data
to your route config to told which page you like to make it remembered (reuseKey
is unique key for your specific each route which use the same component.){ path: '', data: { reuseRoute: true, reuseKey: 'some_key' }, component: MainComponent, },