Angular:依赖注入

140 阅读1分钟

创建服务

import { Injectable } from '@angular/core';
// 注射器
@Injectable({
  // providedIn: 'root' 告诉 Angular在根注入器中注册这个服务,这也是使用CLI生成服务时默认的方式.
  providedIn: 'root',	// 跟注入器,可以在全局使用
  // 这种方式注册,不需要再 @NgModule 装饰器中写 providers,而且在代码编译打包时,可以执行摇树优化,会移除所有没在应用中使用过的服务。推荐使用此种方式注册服务
})
export class HeroService { 
  constructor() { }
  heros = [
	{ id: 1, name: '老亚瑟' }
  ]
  // 新增加setName方法
  setHero(hero) {
	this.heros.push(hero)
  }
  getHeros() {
  	return this.heros
  }
}

使用服务

import { Component, OnInit } from '@angular/core';
import { HeroService } from '../hero.service'
 
@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
  // 往构造函数中添加一个私有的 heroService,其类型为 HeroService。
  // 这个参数同时做了两件事:1. 声明了一个私有 heroService 属性,
  //					 2. 把它标记为一个 HeroService 的注入点。
  constructor(private heroService: HeroService) { }
  // 当 Angular 创建 HeroesComponent 时,依赖注入系统就会把这个 heroService 参数设置为 HeroService 的单例对象。
 
  ngOnInit() {
  	// 使用服务
    this.heroService.setName('张三');
  }
}

注册服务的三种方式

在Angular中有很多方式可以将服务类注册到注入器中:

  • @Injectable 元数据中的providedIn属性
  • @NgModule 元数据中的 providers属性
  • @Component 元数据中的 providers属性

注册在哪里就会在哪里生成一个实例,如果是AppModule则会全局共享,如果是注册在组件则调用一次组件生成一个实例