angularangular-routingangular-routerangular-router-params

Angular route params in service


I need to get route param in my service

import {Inject, Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
import {ActivatedRoute, NavigationEnd, Router} from '@angular/router';

@Injectable({
  providedIn: 'any'
})
export class LocationService {

  constructor(
    private router: Router,
    private route: ActivatedRoute
  ) {
    console.log('ddd ', );

    this.router.events.subscribe((data) => {
      if (data instanceof NavigationEnd) {
        console.log('this.route.snapshot.params[\'city\']; ', this.route.firstChild.snapshot.params['city']);
      }
    });
  }
}

in component that

this.router.events.subscribe((data) => {
  if (data instanceof NavigationEnd) {
    console.log('this.route.snapshot.params[\'city\']; ', this.route.firstChild.snapshot.params['city']);
  }
});

works correctly but in the service city is undefined

If I provide Location service in the component

@Component({
  selector: 'app-city-chooser',
  templateUrl: './city-chooser.component.html',
  styleUrls: ['./city-chooser.component.scss'],
  providers: [LocationSerivce]
})

my service calls twice (i use my service in different component)

How to get route params in my service?


UPD: project has two modules!!! BasicModule and DashboardModule


Solution

  • You can pass params into service method and do whatever you want, getting route params inside service is not a good approach we should avoid it.

    export class LocationService {
     constructor() {}
     
     doSomething(param) {
      // write your logic here
      console.log(param)
     }
    

    In component

    constructor(private route: ActivatedRoute, private service: LocationService) {
       const params = this.route.snapshot.params['city'];
       this.service.doSomething(params)
    }
    

    Hope this works.