'Subscribe to changes to a part of the router URL

Say I have a link localhost:4200/details/1 I want to subscribe only to changes in the "details" part of the URL. i.e. when "details" changes to some other word and not the other parts of the URL. How do I do it?

Edit: So I have found a way but I'm not sure if it is the right way to do it. For some reason ActivatedRoute properties aren't holding any values(either empty or undefined). So I had to use Router.

currentSection: string;
constructor(private router: Router){
      router.events
      .pipe(
        filter(event => event instanceof NavigationEnd &&
          router.url.split('/')[1] != this.currentSection),
      )
      .subscribe((val) => {
        console.log(this.currentSection, router.url.split('/')[1]); 
        this.currentSection = router.url.split('/')[1];
      });
}
ngOnInit(){
 this.currentSection = this.router.url.split('/')[1];
}


Solution 1:[1]

You have to

  1. Subscribe to all changes
  2. Map to required property
  3. use distinctUnilChanged operator

eg.

private route:ActivatedRoute
    this.route.params.pipe(
      map(params => params.yourParamName),
      distinctUntilChanged(),
    ).subscribe(changedParam => console.log(`reacting to single param change ${changedParam}`));

Solution 2:[2]

You can subscribe to the activatedRoute url, and just get the first segment. Ref. example -> hero-detail.component.ts

You can track changes to this between components by implementing a service to which you pass the path.


import { ActivatedRoute, ParamMap } from '@angular/router';
//.....

  constructor(
    private route: ActivatedRoute
  ) {}

  ngOnInit(): void {
    this.route.url.subscribe(m =>console.log(m[0].path)) // this logs "detail"
  }
//....

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Antoniossss
Solution 2