daniel
daniel

Reputation: 35733

Angular ActivatedRoute params subscription in parent component only fired once

I have a container Component AdminComponent which has different childs:

{
    path: ":company/admin",
    component: AdminComponent,
    children: [
      { path: "", component: LoginComponent },
      { path: "account", component: AccountComponent, canActivate: [RedirectGuard] },
      { path: "detail", component: AdminlayoutsComponent, canActivate: [RedirectGuard] }
    ]
}

But my route subscription is only fired once and not on route change:

export class AdminComponent {

  constructor(  private activatedRoute: ActivatedRoute ) {
    this.activatedRoute.params.subscribe((params: Params) => {
      console.log("####params", params);
  });
}
}

How can I trigger the route change event on every route change in my parent component?

Upvotes: 0

Views: 940

Answers (2)

daniel
daniel

Reputation: 35733

events are not fired because: in path: ":company/admin", only first part of path is the param. Right event listener is:

  router.events.subscribe((val) => { 
// do stuff
)};

Upvotes: 0

user4676340
user4676340

Reputation:

In Angular, every route is its own instance.

This means that if you want to listen to the params of the child, you have to listen to the child of the route you're on.

Here is a demo showing it.

  constructor(private route: ActivatedRoute) {
    route.children[0].params.subscribe(params => { console.log(params); });
  }

Although I should warn you, this isn't a very good practice, because the parent not always know if the child is there (while the opposite isn't true). You should just listen to routing events in the child component.

Upvotes: 1

Related Questions