[Angular] 笔记 11:可观察对象(Observable)

chatgpt:

在 Angular 中,Observables 是用于处理异步数据流的重要工具。它们被广泛用于处理从异步操作中获取的数据,比如通过 HTTP 请求获取数据、定时器、用户输入等。Observables 提供了一种机制来订阅这些数据流,并可以在数据到达时执行相应的操作。其优势在于能够处理异步操作、多个事件以及数据的转换和组合,使得对数据流的处理更为灵活和高效。在 Angular 中,Observables 常用于处理 HTTP 请求、与路由、表单和事件处理等方面。


当涉及 Observable,20%的知识覆盖了80%的应用场景。

Observable在代码中被广泛应用于异步操作。

异步操作在前端确保 UI 界面不会冻结,在后端能够提高系统性能。

Observer 和 Observable 之间的关系:

接下来安装一个用于测试的后端: json-server.

vscode terminal 运行: npm i -g json-server,这里必须有 -g,否则后面的 json-server 命令会无法识别。

然后在项目的根目录 创建文件 db.json

db.json 文件内容:

json 复制代码
{
  "pokemon": [
    {
      "id": 1,
      "name": "pikachu",
      "type": "electric",
      "isCool": false,
      "isStylish": true
    },
    {
      "id": 2,
      "name": "squirtle",
      "isCool": true,
      "isStylish": true
    },
    {
      "id": 3,
      "name": "charmander",
      "type": "fire",
      "isCool": true,
      "isStylish": false
    }
  ]
}

vscode terminal 运行命令:

json-server --watch db.json

sh 复制代码
PS D:\Angular\my-app> json-server --watch db.json

  \{^_^}/ hi!

  Loading db.json
  Done

  Resources
  http://localhost:3000/pokemon

  Home
  http://localhost:3000

访问 http://localhost:3000/pokemon,可以看到用于测试的数据:

pokeman-base.module.ts 文件中 import HttpClientModule:

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';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [PokemonListComponent, PokemonDetailComponent],
  imports: [CommonModule, HttpClientModule],  // Add HttpClientModule!!!
  exports: [PokemonListComponent, PokemonDetailComponent],
  providers: [PokemonService],
})
export class PokemonBaseModule {}

接下来访问 http client, pokemon.service.ts:

ts 复制代码
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'; // 新增 import
import { Pokemon } from '../models/pokemon';
import { Observable } from 'rxjs';

// endpoint
const POKEMON_API = 'http://localhost:3000/pokemon';

@Injectable({
  providedIn: 'root',
})
export class PokemonService {
  constructor(private http: HttpClient) {}

  getPokemons(): Observable<Pokemon[]> {
    return this.http.get<Pokemon[]>(POKEMON_API);
  }
}

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();
    this.pokemonService.getPokemons().subscribe((data: Pokemon[])=>{
      console.log(data)
      this.pokemons = data;
    })
  }
}

运行 ng serve:


Angular for Beginners

相关推荐
又見山21 分钟前
用 Obsidian 写了两年的笔记,怎么备份?怎么同步到其他设备上
笔记·obsidian·obsidian插件·obsidian同步·obsidian教程
平头哥技术团队31 分钟前
Day 16 | 用 ul、ol、li 一个标签,把散资料收成有序的技能清单页
开发语言·前端·html·html5
zihan51838 分钟前
理论:构建“基于客观事实、可量化、闭环自给自足”的个人操作系统
笔记·职场和发展·学习方法
代码青铜z39 分钟前
不会写代码做小程序,模板开发和AI 编程靠谱吗?创业前先看这 5 件事
前端
小傅哥1 小时前
Java + DDD,1:1 复刻 Deepseek Harness 项目
前端·后端·ai编程
Z5998178411 小时前
c#软件开发学习笔记--WPF(MVVM框架)
笔记·学习·c#
积硅步致千里1 小时前
Word 里的 .wmf 其实是 EMF:一次 metafile 转 PNG 排障
前端·后端
mayaairi1 小时前
Vue2 组件通讯(二):ref、自定义事件与provide/inject实战
前端·javascript·vue.js
hgfsjk1 小时前
跨境电商ERP系统软件哪个好?2026年选型指南
大数据·经验分享·笔记·其他
开开心心就好1 小时前
PDF图片去水印软件,支持批量处理页面
前端·javascript·人工智能·智能手机·pdf·语音识别