我有一个服务实现类:
export class MyNewService {
seed: number;
text: 'NewService';
constructor(){
this.seed = Number((Math.random() * 100).toFixed(0));
console.log('diablo constructor called: ' + this.seed);
}
}
在app.module.ts里providers区域的定义其作为 token MyService 的实现 :
测试场景1
MyNewService
前面未加任何@Injectable的注解。
测试结果:
NullInjectorError: No provider for MyNewService!
测试场景2
MyNewService前面加上@Injectable的注解。
仍然一样的错误:
测试场景3
@Injectable({ providedIn: 'root' })
这次没有报错了:
测试场景4
把useExisting改成useClass:
对应的MyNewService实例化的代码则在这里调用:
测试场景5
对于同一个injection token,使用useExisting提供多个provider:
测试发现,后
出现在providers数组里的provider定义生效:
而且只有后出现的provider的构造函数会被调用。
测试场景6 加上useExisting, multi: true
很有意思,这一次,MyNewService和MyNewerService的构造函数都触发了:
这次parameter1变成一个数组了:
@Injectable({
providedIn: 'root',
})
export class WindowRef {
readonly document: Document;
注解 @Injectable 的作用:
Determines which injectors will provide the injectable, by either associating it with an @NgModule or other InjectorType, or by specifying that this injectable should be provided in one of the following injectors:
- ‘root’ : The application-level injector in most apps.
- ‘platform’ : A special singleton platform injector shared by all applications on the page.
- ‘any’ : Provides a unique instance in each lazy loaded module while all eagerly loaded modules share one instance.
Marking a class with @Injectable ensures that the compiler will generate the necessary metadata to create the class’s dependencies when the class is injected.
@Injectable 的含义是,当被注解的 class 被注入时,编译器会生成必要的元数据,以创建类的依赖。
更多Jerry的原创文章,尽在:“汪子熙”: