Angular 2 get routeParams in a service

We can pass ActivatedRoute to service from component. Then subscribe to route.params in service class


Acording to this you have to traverse down the route tree and get the data from the route at the bottom of the tree.

@Injectable()
export class MyService{

  constructor(private router:Router,private route:ActivatedRoute){   
   this.router.events
    .filter(event => event instanceof NavigationEnd)
     .subscribe((event) => {
         let r=this.route;
         while (r.firstChild) {
            r = r.firstChild
        }
         //we need to use first, or we will end up having
         //an increasing number of subscriptions after each route change.   
         r.params.first().subscribe(params=>{                
           // Now you can use the params to do whatever you want
         });             


    });            
  }
}

Something like this works for me in Angular 8:

export class TheService {

  params$: Observable<any>;

  constructor(private router: Router) {
    this.params$ = this.router.events.pipe(
      filter(event => event instanceof NavigationEnd),
      map(event => this.getLeafRoute(this.router.routerState.root).snapshot.params)
    );
  }

  private getLeafRoute(route: ActivatedRoute): ActivatedRoute {
    if (route === null) return null; //or throw ?
    while (route.firstChild) route = route.firstChild;
    return route;
  }
}