Angular Service依赖注入的一个具体例子
Angular service 相當于 SAP Commerce Cloud 里的 service facade.
使用如下的命令行創建Angular service:
ng generate service hero
默認生成的hero.service.ts
You must make the HeroService available to the dependency injection system before Angular can inject it into the HeroesComponent by registering a provider. A provider is something that can create or deliver a service; in this case, it instantiates the HeroService class to provide the service.
Provider負責實例化 service.
看這段TypeScript代碼:
@Injectable({providedIn: 'root', })When you provide the service at the root level, Angular creates a single, shared instance of HeroService and injects into any class that asks for it. Registering the provider in the @Injectable metadata also allows Angular to optimize an app by removing the service if it turns out not to be used after all.
一個最佳實踐:
While you could call getHeroes() in the constructor, that’s not the best practice.
Reserve the constructor for simple initialization such as wiring constructor parameters to properties. The constructor shouldn’t do anything. It certainly shouldn’t call a function that makes HTTP requests to a remote server as a real data service would.
Instead, call getHeroes() inside the ngOnInit lifecycle hook and let Angular call ngOnInit() at an appropriate time after constructing a HeroesComponent instance.
盡量不要在構造函數里編寫任何應用邏輯,而是把這些邏輯放到生命周期鉤子 ngOnInit里。
在需要使用service 的Component里,首先import service的實現:
使用構造函數參數的方式進行依賴注入:
The parameter simultaneously defines a private heroService property and identifies it as a HeroService injection site.
構造函數參數注入之后,自動生成一個私有的屬性,名為heroService,就可以使用該服務了。
運行時效果:
從運行時可以看到,Component構造函數里通過參數完成依賴注入,可以通過this.heroService直接訪問注入的服務。
在service的構造函數里設置一個斷點,就能觀察到Angular框架是在何時實例化這個服務實例的:
要獲取更多Jerry的原創文章,請關注公眾號"汪子熙":
總結
以上是生活随笔為你收集整理的Angular Service依赖注入的一个具体例子的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Chrome扩展应用Angular st
- 下一篇: 抖音火山版登录设备在哪里看