Skip to content
This repository has been archived by the owner on Feb 26, 2024. It is now read-only.

this.route.navigate function is not working as expected #446

Open
zk94007 opened this issue Oct 30, 2019 · 0 comments
Open

this.route.navigate function is not working as expected #446

zk94007 opened this issue Oct 30, 2019 · 0 comments

Comments

@zk94007
Copy link

zk94007 commented Oct 30, 2019

I'm using Angular 8 and faced some problems with routing when I'm using lazy-loaded child modules.

app-routing.module.ts

...
const routes: Routes = [
   {
      path: :id,
      component: ParentComponent,
      children: [
         { path: 'child', loadChildren: './child.module#ChildModule' }
      ]
   }
]
...

child-routing.module.ts

...
const routes: Routes = [
   { path: 'child1', component: Child1Component },
   { path: 'child2', component: Child2Component }
]
...

Now, we have routing in these ways.
foo.com/123/child/child1 -> Child1Component
foo.com/123/child/child2 -> Child2Component

Here, I tried to navigate to foo.com/123/child/child2 inside Child1Component.
I was thinking child module is apart from app module and it's lazy loaded so this code will be working correctly.

child2.component.ts

...
constructor(private router: Router) {}

...
this.router.navigate(['child/child2']);
...

But once I launched the application, it is navigated to foo.com/child/child2.
I was expecting foo.com/123/child/child2.

If I make these changes, it's working as expected.

child2.component.ts

...
private parentId;
constructor(private router: Router, private route: ActivatedRoute) {
   this.route.parent.parent.params.subscribe((params) => {this.parentId = params.id});
}

...
this.router.navigate([this.parentId, 'child', 'child2']);
...

It's getting parentId from the URL inside the component and navigate using it.
But I don't like this approach because it's not scalable.
If I change the Route Param name or add some more routing params, I have to update the child components for routing as well.

Is there any better approach for handling routing in child components defined on child module lazy-loaded?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant