RxJS 高阶映射操作符详解:map、mergeMap 和 switchMap

1. map 操作符

map 是最基本的转换操作符,用于对 Observable 发出的每个值进行一对一转换。

基本特点:

  • 同步操作
  • 一对一转换
  • 不改变 Observable 的发出时机

详细示例:

import {
   
    of } from 'rxjs';
import {
   
    map } from 'rxjs/operators';

// 示例1:简单数值转换
of(1, 2, 3).pipe(
  map(x => x * 2)
).subscribe(result => console.log(result));
// 输出: 2, 4, 6

// 示例2:对象属性转换
const users = of(
  {
   
    id: 1, name: 'Alice', age: 25 },
  {
   
    id: 2, name: 'Bob', age: 30 }
);

users.pipe(
  map(user => ({
   
   
    ...user,
    name: user.name.toUpperCase(),
    isAdult: user.age >= 18
  }))
).subscribe(console.log);
/* 输出:
{id: 1, name: "ALICE", age: 25, isAdult: true}
{id: 2, name: "BOB", age: 30, isAdult: true}
*/

// 示例3:API响应处理
import {
   
    from } from 'rxjs';

function fetchUser(userId) {
   
   
  return from(
    fetch(`https://jsonplaceholder.typicode.com/users/${
     
     userId}`)
      .then(response => response.json())
  );
}

fetchUser(1).pipe(
  map(user => user.name)
).subscribe(name => console.log('用户名:', name));
// 输出: 用户名: Leanne Graham

2. mergeMap (flatMap) 操作符

mergeMap 用于将一个值映射成一个新的 Observable,并同时订阅所有这些内部 Observable,合并它们的输出。

基本特点:

  • 一对多转换
  • 同时维护多个内部订阅
  • 不取消之前的订阅
  • 适合并行处理

详细示例:

import {
   
    of, interval } from 'rxjs';
import {
   
    mergeMap, take } from 'rxjs/operators';

// 示例1:将每个值转换为新的Observable
of('a', 'b', 'c').pipe(
  mergeMap(letter => 
    interval(1000).pipe(
      take(3),
      map(i => letter + i)
    )
  )
).subscribe(console.log);
/* 输出 (每秒一个):
a0
b0
c0
a1
b1
c1
a2
b2
c2
*/

// 示例2:实际API请求
function fetchPosts(userId) {
   
   
  return from(
    fetch(`https://jsonplaceholder.typicode.com/posts?userId=${
     
     userId}`)
      .then(response => response.json(
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值