Injectable
标记性元数据,表示一个类可以由 Injector
进行创建。
A marker metadata that marks a class as available to Injector
for creation.
选项 | 说明 |
---|---|
providedIn |
说明
欲知详情,参见"依赖注入"。
For more details, see the "Dependency Injection Guide".
使用说明
范例
Example
@Injectable()
class UsefulService {
}
@Injectable()
class NeedsService {
constructor(public service: UsefulService) {}
}
const injector = ReflectiveInjector.resolveAndCreate([NeedsService, UsefulService]);
expect(injector.get(NeedsService).service instanceof UsefulService).toBe(true);
Injector
在试图实例化一个不带 @Injectable
标记的类时,就会抛出一个错误,如下面的例子所示。
Injector
will throw an error when trying to instantiate a class that does not have @Injectable
marker, as shown in the example below.
class UsefulService {}
class NeedsService {
constructor(public service: UsefulService) {}
}
expect(() => ReflectiveInjector.resolveAndCreate([NeedsService, UsefulService])).toThrow();