Jack
Jack

Reputation: 1

How to keep route parameters even page refresh

I use the following approach to pass parameters through different routes and I am trying to keep these parameter values on page refresh or opening another tab on the routed page. However, after retrieving these parameters, they lost their values. So, is it possible to keep their values without using :id etc suffix on the routes? In this scenario, I open the SecondComponent first and then open its Child called SecondChildComponent using tabs.

first.component.ts

details(name) {
    this.router.navigate(['/second'], { state: { name: name} });
}

second.component.ts

constructor(private router: Router) {
   this.name= this.router.getCurrentNavigation().extras.state.name;
}

routing.module

const routes: Routes = [
  {
    path: 'second',
    component: SecondComponent,
    children: [
      {
        path: '',
        redirectTo: 'second-child',
      },
      {
        path: 'second-child',
        component: SecondChildComponent
      }
    ]
  }
];

Upvotes: 1

Views: 4646

Answers (1)

Eliseo
Eliseo

Reputation: 58039

I'm afraid that your code don't work as you expect, please read this link about pass data using state

The brief idea is that you can get the value of the state

In the component where you go

ngOnInit() {
    this.activatedRoute.paramMap
      .pipe(map(() => window.history.state)).subscribe(res=>{
        console.log(res)
    })
  }

In the "main component" using

ngOnInit() {
    this.router.events.pipe(
      filter(e => e instanceof NavigationStart),
      map(() => this.router.getCurrentNavigation().extras.state)
    ).subscribe(res=>{
       console.log(res)
    })
  }

Well about your question, the only "object" that maintain when you change the route is a "service". The only "object" that maintain when you "refresh" is localStore -or use some king of back-up in the server.

Using a service, simply has

@Injectable({
  providedIn: 'root',
})
export class DataService {

  data:any;
  constructor() { }

}

And use

    .subscribe(res=>{
        this.dataService.data=res.name || this.dataService.data
        this.name=this.dataService.data
    })

Another aproach is if you don't receive a parameter router to first component. This idea can use e.g. if you has a typical component with a table with a button edit that links to a "detail" component. If the "detail" don't receive the value route to the component with the table

    .subscribe(res=>{
        if (!res.name)
           this.router.navigateTo(['/table'])
    })

Upvotes: 1

Related Questions