[Angular] 笔记 10:服务与依赖注入

什么是 Services & Dependency Injection?

chatgpt 回答:


在 Angular 中,Services 是用来提供特定功能或执行特定任务的可重用代码块。它们可以用于处理数据、执行 HTTP 请求、管理应用程序状态等。Dependency Injection(依赖注入)是 Angular 框架用来管理组件之间依赖关系的机制。通过依赖注入,Angular 能够将一个对象实例注入到另一个对象中,使得组件可以访问所需的服务或其他依赖项,这样可以更轻松地管理代码、提高可维护性,并促进代码重用。在 Angular 中,通过依赖注入将服务注入到组件中,使得组件能够使用这些服务的功能而无需自己创建实例或处理其生命周期。


Youtube Tutorial:

当前的 Angular app 中有 list 组件和 detail 组件,pokemons 数组放在list 组件中,这是一种非常糟糕的设计模式,即使这只是一个小小的 pokemon app。

接下来要做的是,抽象化 pokemons 数组,将其改成一个服务,之后就可以将此服务注入到 app 其他任意位置。

1 创建服务

1.1 有很多方法,例如 vscode terminal 运行命令:

ng g service <my-service-name>

1.2 或者使用 Angular Files extension:

首先在 app 文件夹下新建一个文件夹 services,右键此 services 文件夹,选择 Generate Service,服务名称设为 pokemon:

项目结构:

2 将服务加到 module 里

pokemon-base.module.ts:

ts 复制代码
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { PokemonListComponent } from './pokemon-list/pokemon-list.component';
import { PokemonDetailComponent } from './pokemon-detail/pokemon-detail.component';
import { PokemonService } from '../services/pokemon.service';

@NgModule({
  declarations: [PokemonListComponent, PokemonDetailComponent],
  imports: [CommonModule],
  exports: [PokemonListComponent, PokemonDetailComponent],
  providers: [PokemonService],  // providers 中增加新建 service
})
export class PokemonBaseModule {}

3 service 里创建整个 app 都可使用的函数

pokeman.service.ts

ts 复制代码
import { Injectable } from '@angular/core';
import { Pokemon } from '../models/pokemon';

@Injectable({
  providedIn: 'root',
})
export class PokemonService {
  constructor() {}
  
  // 此函数整个 app 都可以使用
  getPokemons(): Pokemon[] {
    return [
      // Pokemon: 精灵宝可梦
      {
        id: 1,
        name: 'pikachu', // 皮卡丘
        type: 'electric',
        isCool: false,
        isStylish: true,
      },
      {
        id: 2,
        name: 'squirtle', // 杰尼龟
        type: 'water',
        isCool: true,
        isStylish: true,
      },
      {
        id: 3,
        name: 'charmander', // 小火龙
        type: 'fire',
        isCool: true,
        isStylish: false,
      },
    ];
  }
}

同时,删除 pokeman-list.component.ts 中对应的 pokemons 数组。

4 依赖注入

需要用到依赖注入时,就将依赖注入放进构造函数中。

pokeman-list.component.ts 完整代码如下:

ts 复制代码
import { Component, OnInit } from '@angular/core';
import { Pokemon } from 'src/app/models/pokemon';
import { PokemonService } from 'src/app/services/pokemon.service';

@Component({
  selector: 'app-pokemon-list',
  templateUrl: './pokemon-list.component.html',
  styleUrls: ['./pokemon-list.component.css'],
})
export class PokemonListComponent implements OnInit {
  pokemons!: Pokemon[];

  // 修改 constructor
  constructor(private pokemonService: PokemonService) {}

  handleRemove(event: Pokemon) {
    this.pokemons = this.pokemons.filter((pokemon: Pokemon) => {
      return pokemon.id !== event.id;
    });
  }

  ngOnInit(): void {
    // 填充 pokemons 属性
    this.pokemons = this.pokemonService.getPokemons();
  }
}

运行 ng serve, 可以删除 pokemon, console 也没有错误, 这说明服务确实在运行。

相关推荐
学习使我快乐012 小时前
JS进阶 3——深入面向对象、原型
开发语言·前端·javascript
bobostudio19952 小时前
TypeScript 设计模式之【策略模式】
前端·javascript·设计模式·typescript·策略模式
黄尚圈圈3 小时前
Vue 中引入 ECharts 的详细步骤与示例
前端·vue.js·echarts
浮华似水4 小时前
简洁之道 - React Hook Form
前端
正小安6 小时前
如何在微信小程序中实现分包加载和预下载
前端·微信小程序·小程序
_.Switch8 小时前
Python Web 应用中的 API 网关集成与优化
开发语言·前端·后端·python·架构·log4j
一路向前的月光8 小时前
Vue2中的监听和计算属性的区别
前端·javascript·vue.js
长路 ㅤ   8 小时前
vite学习教程06、vite.config.js配置
前端·vite配置·端口设置·本地开发
长路 ㅤ   8 小时前
vue-live2d看板娘集成方案设计使用教程
前端·javascript·vue.js·live2d
Fan_web8 小时前
jQuery——事件委托
开发语言·前端·javascript·css·jquery