在Angular中注入通用服务 [英] Injection of Generic Services in Angular
问题描述
如果在使用不同类型的组件构造函数中调用通用服务,Angular会注入多个实例吗?
Will Angular inject more than one instance of a generic Service if it is invoked across Component constructors using different Types?
我有很多服务将为从同一基类继承的不同类提供相同的功能.我想使用Typescript的通用模式MyService<T extends BaseClass>
来解决这个问题.
I have a lot of Services that are going to provide the same functionality for different classes that all inherit from the same base class. I'd like to use Typescript's generic pattern MyService<T extends BaseClass>
to handle this.
但是我不知道它如何与Angular的喷油器配合使用
But I don't know how it jives with Angular's injector:
- 如果将Angular注入器注入到具有不同类型的不同组件中,是否会为其创建个以上实例?
- 如果相同类型的调用,注入器会注入相同的实例吗?
- Will the Angular injector create more than one instance of this service if it's injected into different components with different Types?
- Will the injector inject the same instance if it is called with the same type?
代码:
@Injectable
export class MyService<T> {
...
}
@Component
export class ComponentA {
constructor(alphaService MyService<Alpha>) {} <--Instance 1
}
@Component
export class ComponentB {
constructor(betaService MyService<Beta>) {} <----Instance 2?
}
@Component
export class ComponentA1 {
constructor(alphaService MyService<Alpha>) {} <---Instance 1?
}
这合法吗?注入器是否知道创建MyService的两个实例?
Is this legal? Does the injector know to create two instances of MyService?
推荐答案
这是一个简单的解决方案:
This is a simple solution:
// service and models
export class User {
firstName: string
}
export class Admin {
lastName: string
}
@Injectable()
export class GenericService<T>{
item: number = Math.random();
GetAll(): Array<T> {
let output = [];
console.log(this.item); // each instance has own value
return output;
}
}
然后通过useFactory在模块中设置服务:
Then set your service in module through useFactory:
providers: [
{ provide: 'UserService', useFactory: () => (new GenericService<User>()) },
{ provide: 'AdminService', useFactory: () => (new GenericService<Admin>()) },
],
并使用@Inject装饰器注入服务:
and inject your service with @Inject decorator:
constructor(
@Inject('UserService') private userService: GenericService<User>,
@Inject('AdminService') private adminService: GenericService<Admin>
) { }
请记住,最好使用 InjectionToken (
Keep in mind it is better to use InjectionToken ( OpaqueToken is deprecated) for your provider token.I have used string just for simplicity.
这篇关于在Angular中注入通用服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!