在非Angular类中获取注入的依赖项 [英] Get an injected dependency in a non-Angular class
问题描述
我拥有当前(并简化的)课程:
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 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);
}
}
因为它使用了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屋!