angular / router

The Angular 1 Component Router
MIT License
665 stars 135 forks source link

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

Open zk94007 opened 4 years ago

zk94007 commented 4 years ago

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
```typescript
...
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?