在非Angular类中获取注入的依赖项 [英] Get an injected dependency in a non-Angular class

查看:96
本文介绍了在非Angular类中获取注入的依赖项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我拥有当前(并简化的)课程:

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.

有办法吗?我想到了

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 ?

推荐答案

您可以创建一个工厂服务来处理NavigationItem的创建,并将它们与Router连接起来.以下是NavigationItemFactory类的外观示例:

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);
    }
}

因为它使用了Angular 6+的providedIn功能,所以您不需要在模块中声明此工厂类,这使得它可以在项目之间轻松移动.

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.

要在项目中创建这些项目的任何地方,只需依赖NavigationItemFactory并相应地使用其createItem功能即可.当然,这仍然是您在项目中需要的依赖项,但至少现在它是对您自己的类型的依赖,而不是Router本身.

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.

这篇关于在非Angular类中获取注入的依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆