日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Angular Service依赖注入的一个具体例子

發布時間:2023/12/19 编程问答 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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依赖注入的一个具体例子的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。