I have the current (& simplified) class :
export class NavigationItem {
constructor(
private router: Router
) {}
navigateTo() { this.router.navigate([this.id]); }
}
I would like not to have to inject myself the router everytime I declare a new instance of this class.
Is there a way of doing so ? I thought about something along the lines of
export class NavigationItem {
@Inject(forwardRef(() => Router))
private _router: Router;
constructor() {}
navigateTo() { this.router.navigate([this.id]); }
}
But it doesn't seem to work. Any idea ?
You could create a factory service that handles creation of
NavigationItem
s and wires them up with theRouter
. Here's an example of what aNavigationItemFactory
class might look like:Because this uses Angular 6+'s
providedIn
feature, you don't need to declare this factory class in a module, which makes it easily movable between projects.Anywhere you want to create these items in your project, just take a dependency on
NavigationItemFactory
and use itscreateItem
function accordingly. Granted, this is a still a dependency you'll need in your project but at least it's now a dependency on your own type rather thanRouter
itself.