Angular -- Service & Dependency Injection

本文详细介绍了Angular服务的使用,包括如何通过@Injectable装饰器声明服务,如何在不同级别(根、模块、组件)提供服务,以及服务的注入机制。服务是Angular应用中实现特定功能的类,可以被组件和指令依赖。通过组件构造函数注入服务,使得组件能够使用服务的功能。
摘要由CSDN通过智能技术生成

 Service

  • A service is typically a class with a narrow, well-defined purpose. It should do something specific and do it well.
  • Every module is defined with a @Injectable decorator.
  • Then you can inject a service into a component, giving the component access to that service class.
  • Cli: ng g s <service name> 

      import { Injectable } from '@angular/core';
 
      @Injectable({
        providedIn: 'root'
      })
      export class TestServiceService {
 
        constructor() { }
 
      }

Definition:

  • Dependencies -- services which have a functionality, but not limited to services
  • Functionality -- Something needed by components and directives in the application
  • Injection -- A mechanism provided by Angular to provide services to components and directives

Dependency

An Angular service declared with an @Injectable decorator.

@Injectable({ 
    providedIn: 'root'
})

Providing

Register provider at a specific level to limit the service availability.

Root level 

This allows the service to be have global availability.

To do this, you register in the service class itself:

@Injectable({
 providedIn: 'root',
})

Module level

This allows the service to be available in a particular module.

To do this, you register in the module class:

@NgModule({
  providers: [
  BackendService,
  Logger
 ],
 …
})

Component level

This allows the service to be available in a particular component.

To do this, you register in the component class:

@Component({
  selector:    'app-hero-list',
  templateUrl: './hero-list.component.html',
  providers:  [ HeroService ]
})

Injection

  • In the component needing the service
    1. Import the service class
    2. Declare an instance of the class
  • Boom! the service is now usable in the component!
import { XXXService } from '.....';
/* ... */
constructor(private xxxService:XXXService) { }

Under the hood injection machanism:

  • XXXService is registered as a component dependency
  • Angular search the injector for existing service instance
    • if exist, return and inject that instance
    • if not, use provider (service class) to create instance then inject

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值