Home > Software engineering >  Getting ID of parent route consistently in child with observable
Getting ID of parent route consistently in child with observable

Time:10-16

Assuming I have this route.

/main/users/2/tables

How to make sure that the child route tables picks up a change in the param ID of parent route /users/2 with an observable?

So in tables route component:

ngOnInit() {
    this.usersService.watchUser()
     .pipe(
       takeUntil(this.onDestroy),
       tap((user)=> {
         console.log(user['id']);
       })
     ).subscribe();
    
}

and in users/1 route:

    const userId = this.route.snapshot.paramMap.get('id');

    this.usersService.currentUser$.next({id: userId}); 

How to make sure that tables observable is called once only and changes everytime ID changes in the users/1 route automatically?

Thank you

CodePudding user response:

You can access the parent's params using the ActivatedRoute instance like this:

constructor(private route: ActivatedRoute) {}

ngOnInit() {
  this.route.parent?.params.subscribe(params => {
    console.log(params['id']) // do whatever you want with the params
  });
}
  • Related