Reputation:
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 ?
Upvotes: 3
Views: 89
Reputation: 93053
You could create a factory service that handles creation of NavigationItem
s and wires them up with the Router
. Here's an example of what a NavigationItemFactory
class might look like:
// imports
@Injectable({ providedIn: 'root' })
export class NavigationItemFactory {
constructor(private router: Router) { }
createItem(): NavigationItem {
return new NavigationItem(this.router);
}
}
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 its createItem
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 than Router
itself.
Upvotes: 3