0

I've read that using a router in a service is bad practice in another question. I understand the point, that it's better to use it in a component because here I have direct access to the users interaction, but I am wondering if in my case it would be better to use the router in a service:

I have a web-app where I want to navigate to different elements. Depending on how the user navigated to the element I want to have a different behaviour. In the component, to which I navigate I want to check which navigation was done. Currently I do this with a flag, that gets set before I navigate to the component.

So I have different parts of code that work like this:

Navigation 1:

this.someFlagService.alternativeNavigation = true; //set flag to true
this.router.navigate(['/componentToNavigate']); //navigate to component

Navigation 2:

this.someFlagService.alternativeNavigation = false; // set flag to false
this.router.navigate(['/componentToNavigate']); //navigate to component

Component to navigate to:

if(this.someFlagService.alternativNavigation) //do a 
else // do b      

So in every component where I navigate I need to set my flag. I am wondering, that if I'd only navigated from a service, I could just set the flag in my service. I don't really understand, why it would be bad practice to use the router in a central navigation service which holds arguments for the navigation. I don't want to pass some of the arguments as query parameters because it would make the error handling much more difficult when the arguments could take any value.

DerWolferl
  • 71
  • 7
  • 2
    You do not need a service for this one either, Angular routing supports passing data as well. Check this out: https://www.tektutorialshub.com/angular/angular-pass-data-to-route/ – Berk Kurkcuoglu Nov 10 '20 at 13:20
  • You can pass the data directly from the router. Have a look at this. https://stackoverflow.com/questions/36835123/how-do-i-pass-data-to-angular-routed-components – Ali Turab Abbasi Nov 10 '20 at 13:42

0 Answers0