Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 {
            ...
        }
    }
}
like image 894
SMH Avatar asked Sep 06 '18 13:09

SMH


1 Answers

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 {
            ...
        }
    }
}
like image 173
SiddAjmera Avatar answered Sep 20 '22 12:09

SiddAjmera