如何将服务注入类(不是组件) [英] How to inject service into class (not component)
问题描述
我想将服务注入到不是组件的类中.
I want to inject a service into a class that is not a component.
例如:
我的服务
import {Injectable} from '@angular/core';
@Injectable()
export class myService {
dosomething() {
// implementation
}
}
MyClass
import { myService } from './myService'
export class MyClass {
constructor(private myservice:myService) {
}
test() {
this.myservice.dosomething();
}
}
此解决方案不起作用(我认为是因为尚未实例化MyClass
).
This solution doesn't work (I think because MyClass
hasn't been instantiated yet).
在类(不是组件)中还有其他使用服务的方法吗?还是您会认为我的代码设计不合适(在不是组件的类中使用服务)?
Is there another way to use a service in a class (not component)? Or would you consider my code design as inappropriate (to use a service in a class which is not a component)?
谢谢.
推荐答案
注入仅适用于通过Angulars依赖注入(DI)实例化的类.
Injections only works with classes that are instantiated by Angulars dependency injection (DI).
- 您需要
- 将
@Injectable()
添加到MyClass
和 - 在组件或NgModule中提供<c0>像
providers: [MyClass]
一样.
- 将
- You need to
- add
@Injectable()
toMyClass
and - provide
MyClass
likeproviders: [MyClass]
in a component or NgModule.
- add
然后在某个位置注入MyClass
时,通过DI实例化一个MyService
实例(在第一次注入之前)会将该实例传递给MyClass
.
When you then inject MyClass
somewhere, a MyService
instance gets passed to MyClass
when it is instantiated by DI (before it is injected the first time).
- 另一种方法是配置自定义注入器,例如
constructor(private injector:Injector) {
let resolvedProviders = ReflectiveInjector.resolve([MyClass]);
let childInjector = ReflectiveInjector.fromResolvedProviders(resolvedProviders, this.injector);
let myClass : MyClass = childInjector.get(MyClass);
}
这样,myClass
将成为MyClass
实例,由Angulars DI实例化,并且myService
在实例化时将注入到MyClass
中.
另请参见在指令内手动从Injector获取依赖项
This way myClass
will be a MyClass
instance, instantiated by Angulars DI, and myService
will be injected to MyClass
when instantiated.
See also Getting dependency from Injector manually inside a directive
- 另一种方法是自己创建实例:
constructor(ms:myService)
let myClass = new MyClass(ms);
这篇关于如何将服务注入类(不是组件)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!