What is the best way to get current route params in Angular 6 services?

SMH picture SMH · Sep 6, 2018 · Viewed 15.4k times · Source

I am trying to find out what is the best way to get the current route params in Angular 6.

At the moment I have to pass the ActivatedRoute to the service's method as argument and then use it in the service.

export class MainComponent {
    constructor(private dataService: DataService, private activeRoute: ActivatedRoute) { }

    getChartsData() {
        return this.dataService(this.activeRoute);
    }
}

@Injectable({
  providedIn: "root"
})
export class DataService {
    getChartsData(activatedRoute) {
        if (activatedRoute.snapshot.params['id']) {
            ...
        } else {
            ...
        }
    }
}

Answer

SiddAjmera picture SiddAjmera · Sep 6, 2018

Since you want the current route params, instead of activatedRoute.snapshot, you should be subscribing to activatedRoute.params. It will give you the latest and updated value of the current route params.

Your service method should not be responsible for getting the id from the ActivatedRoute. It should be the responsibility of your Component. Your service should only be responsible for getting the id from the component and then do the needful based on that id.

You should be extracting the id from the activatedRoute in your component. And then call the service method by passing it the id

export class MainComponent {
    constructor(
        private dataService: DataService, 
        private activeRoute: ActivatedRoute
    ) { }

    getChartsData() {
        this.activeRoute.params.subscribe(params => {
            if(params['id']) {
                this.dataService.getChartsData(params['id'])
                    .subscribe(data => console.log(data));
            }
        })

    }
}

And in your service

@Injectable({
  providedIn: "root"
})
export class DataService {
    getChartsData(id) {
        if (id) {
            ...
        } else {
            ...
        }
    }
}