关于Angular @Injectable的几种测试情况
我有一個服務實現類:
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的原創文章,盡在:“汪子熙”:
總結
以上是生活随笔為你收集整理的关于Angular @Injectable的几种测试情况的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 泰裤辣!Redmi Note 12 Tu
- 下一篇: Angular 依赖注入 useClas