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(

最低0.47元/天 解锁文章
1748

被折叠的 条评论
为什么被折叠?



