Get an injected dependency in a non-Angular class

时光怂恿深爱的人放手 提交于 2019-12-23 18:36:28

问题


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:


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.



来源:https://stackoverflow.com/questions/53155463/get-an-injected-dependency-in-a-non-angular-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!