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框架是在何时实例化这个服务实例的: