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

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

Angular service 相当于 SAP Commerce Cloud 里的 service facade.

使用如下的命令行创建Angular service:

ng generate service hero

image.png

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的实现:

image.png

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


构造函数参数注入之后,自动生成一个私有的属性,名为heroService,就可以使用该服务了。


运行时效果:

image.png

image.png

image.png

相关文章
|
7月前
|
搜索推荐
Angular 依赖注入错误消息:ERROR Error NullInjectorError No provider for XX
Angular 依赖注入错误消息:ERROR Error NullInjectorError No provider for XX
39 0
|
4月前
|
缓存 前端开发 JavaScript
Angular Service Worker 在 PWA 应用 HTTP 交互中扮演的角色
Angular Service Worker 在 PWA 应用 HTTP 交互中扮演的角色
45 0
|
6月前
|
设计模式 监控 测试技术
Angular 使用 Constructor Parameters 进行依赖注入的优缺点
Angular 使用 Constructor Parameters 进行依赖注入的优缺点
26 0
|
6月前
|
设计模式
Angular 依赖注入领域里 optional constructor parameters 的概念介绍
Angular 依赖注入领域里 optional constructor parameters 的概念介绍
23 0
|
6月前
Angular 依赖注入系统里 Injection token PLATFORM_ID 的使用场景
Angular 依赖注入系统里 Injection token PLATFORM_ID 的使用场景
24 0
|
6月前
|
移动开发 网络架构 HTML5
Angular 依赖注入系统里 Injection token APP_BASE_HREF 的使用场景
Angular 依赖注入系统里 Injection token APP_BASE_HREF 的使用场景
37 0
|
6月前
|
开发者
Angular 两种依赖注入的实现方法介绍
Angular 两种依赖注入的实现方法介绍
33 0
|
8月前
|
Web App开发 缓存 安全
Angular 应用要启用 Service Worker 所需满足的一些前提条件
Angular 应用要启用 Service Worker 所需满足的一些前提条件
61 2
|
8月前
|
缓存 API
Angular 里的 Service Worker
从 5.0.0 版本开始,Angular 附带了一个 Service Worker 实现。 Angular 开发人员可以利用这个 service worker 并从其提供的更高的可靠性和性能中受益,而无需针对低级 API 编写代码。
54 0
|
8月前
|
编译器
Angular 依赖注入机制实现原理的深入介绍
Angular 依赖注入机制实现原理的深入介绍
25 0