I've been using Angular 2/4 for about a year now and I keep returning to this dilemma whether injecting Router into service can be considered as a bad practice?
This is more architectural question. I believe there's no exact answer for it, but I want to hear your opinion. So here are 2 examples.
- Consider the next code. Imagine we have some component and we want to redirect user to specific route after some action, e.g. user added a new entity and we want to redirect him back to the grid.
component.ts
constructor(private router: Router) {}
someAction() {
// Some code here
this.router.navigate(['/grid']);
}
Here I think it's perfectly fine to use Router, because both Router and Component is UI layer.
- Now let's imagine we have
auth.service.ts
and it's responsible for authentication. We want to be able to logout user out of the application and we havelogout()
function to do that.
auth.service.ts
constructor(private router: Router) {}
logout() {
// Cleanup token, storage, etc.
this.router.navigate(['/login']);
}
So thinking architecturally:
- What do you think of such router usage inside the service?
- Do you think it's a valid approach?
- If not what do you suggest in this case?
I was thinking about putting eventEmitter
on authService
and subscribe to it inside app.component.ts for instance, but still not sure if it's better than having it in the service.
I appreciate any comments for this case. Thanks a lot!
EDIT
Another example: UI is a calendar with tasks.
There's a service that handles all data-flow and provides data for the calendar. Calendar itself doesn't ask for the data, instead it subscribes to the data change from the service.
Now I need to route user to a different screen from this calendar. Imagine user clicks next week/month/year.
This data stored in the route URL so user can stay on the same day after page refresh, but calendar component doesn't know about the days/weeks/months.
They are incapsulated inside the service. So will you use router in service in this case?