2

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

Igor Zinchenko
  • 305
  • 3
  • 13

1 Answers1

0

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.

Kamran Khatti
  • 3,754
  • 1
  • 20
  • 31
  • @Karman Khatti, is the correct way to use this.route.firstChild on the parent component? I have two modules and in each module i have main component, each page on my app use that service and i need init it on each page for different url if i put it in the new browser tab – Igor Zinchenko Aug 06 '20 at 10:19
  • so i want to init my service in main module component – Igor Zinchenko Aug 06 '20 at 10:25
  • 1
    I dont know how you implemented if this.route.firstChild works for you go for it its just matter of getting params value – Kamran Khatti Aug 06 '20 at 10:29