天天看點

Angular Service依賴注入的一個具體例子

Angular

service 相當于 SAP Commerce Cloud 裡的 service facade.

使用如下的指令行建立Angular service:

ng generate service hero
Angular Service依賴注入的一個具體例子
預設生成的hero.service.ts
Angular Service依賴注入的一個具體例子

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的實作:

Angular Service依賴注入的一個具體例子

使用構造函數參數的方式進行依賴注入:

Angular Service依賴注入的一個具體例子

The parameter simultaneously defines a private heroService property and identifies it as a HeroService injection site.

構造函數參數注入之後,自動生成一個私有的屬性,名為heroService,就可以使用該服務了。

運作時效果:

Angular Service依賴注入的一個具體例子

從運作時可以看到,Component構造函數裡通過參數完成依賴注入,可以通過this.heroService直接通路注入的服務。

Angular Service依賴注入的一個具體例子

在service的構造函數裡設定一個斷點,就能觀察到Angular架構是在何時執行個體化這個服務執行個體的:

Angular Service依賴注入的一個具體例子

繼續閱讀