How to implement the route relative redirects with the query params and the fragment

2.1k Views Asked by At

I have one problem in developing Angular project.

I tried to find the solution on how to implement the route relative redirects with When the URL redirects, in which origin redirect has its relative the query params and the fragment.

For example, in the guide of Angular.io.

const heroesRoutes: Routes = [
  { path: 'heroes', redirectTo: '/superheroes' },
  { path: 'hero/:id', redirectTo: '/superhero/:id' },
  { path: 'superheroes',  component: HeroListComponent },
  { path: 'superhero/:id', component: HeroDetailComponent }
];

in hero-detail, goback() function to navigate back to the HeroListComponent. I added relativeTo: this.route. But it is not working.

gotoHeroes(hero: Hero) {
  let heroId = hero ? hero.id : null;
  // Pass along the hero id if available
  // so that the HeroList component can select that hero.
  // Include a junk 'foo' property for fun.
  this.router.navigate(['/heroes', { id: heroId, foo: 'foo' }], {relativeTo: this.route});
}

When configuring to redirect to superheroes, I don't know how to implement this feature.

2

There are 2 best solutions below

3
Michael Kang On

You need a relative route, so depending on where you are, this should work to go back:

this.router.navigate(['../', { id: heroId, foo: 'foo' },  {relativeTo: this.route}]);
0
sharad jain On

You can use something like -

 this.router.navigate(
    ['hero','12345'],
    {
      relativeTo: this.route,
      queryParams: {
        type: 'value',
      },
    }
  );