Ivilin Stoyanov
Ivilin Stoyanov

Reputation: 407

Why my router navigate function doesn't work in angular 8?

I'm trying to redirect to another component like this:

HomeComponent

  checkUrl(reference) {   
    if (reference != this.ref) {
      this.router.navigate(['/еrror']);
    }
  }

here is my router module

const routes: Routes = [
  { path: '', component: DefaultComponent },
  {
    path: '',
    children: [
      { path: ':dlr/:id/:ref', component: HomeComponent },
      { path: 'error', component: ErrorPageComponent },
    ]
  },
  { path: '**', redirectTo: '', pathMatch: 'full' }

];

right now I'm in the HomeComponent and want to go to the error page.

this.router.navigate(['/еrror']) this leads me to the DefaultComponent

Upvotes: 1

Views: 1766

Answers (2)

lunar_ninja
lunar_ninja

Reputation: 68

Adding details to a previously deleted answer -

As it is a child to child navigation, you can try adding relativeTo: this.activatedRoute tag. You can find more about its syntax and usage here relativeTo in the documentation. This is basically similar to '../' type of notations that we use for navigation in general while trying to specify the path of a file.

Therefore, you can try something like this - this.router.navigate(['/еrror'], {relativeTo: this.activatedRoute});.

Also, one thing to note here is if you will use ['еrror'] instead of this ['/error'], the navigation can be different. If for example, you are currently here - parent/abc/c1 (where c1 is a child component) and you use ['error'] (where 'error' is the child component of the same parent as c1), the URI will become parent/abc/c1/error whereas if you will use ['/error'], you will be first moved one level up parent/abc/ and then the other child will be added - parent/abc/error.

There are a few other approaches as well described here - RouterNavigation along with the one that I described above, have a look at it. Hope this helps.

Upvotes: 1

Ivilin Stoyanov
Ivilin Stoyanov

Reputation: 407

 this.router.navigate(['/error'], { relativeTo: this.activatedRoute });

adding relativeTo it worked for me.

Upvotes: 2

Related Questions