Get an injected dependency in a non-Angular class

2019-07-01 16:53发布

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 ?

1条回答
走好不送
2楼-- · 2019-07-01 17:23

You could create a factory service that handles creation of NavigationItems 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.

查看更多
登录 后发表回答