map
签名: map(project: Function, thisArg: any): Observable
对源 observable 的每个值应用投射函数。
示例
示例 1: 每个数字加10
( StackBlitz |
jsBin |
jsFiddle )
import { from } from 'rxjs/observable/from';
import { map } from 'rxjs/operators';
// 发出 (1,2,3,4,5)
const source = from([1, 2, 3, 4, 5]);
// 每个数字加10
const example = source.pipe(map(val => val + 10));
// 输出: 11,12,13,14,15
const subscribe = example.subscribe(val => console.log(val));
示例 2: 映射成单一属性
( StackBlitz |
jsBin |
jsFiddle )
import { from } from 'rxjs/observable/from';
import { map } from 'rxjs/operators';
// 发出 ({name: 'Joe', age: 30}, {name: 'Frank', age: 20},{name: 'Ryan', age: 50})
const source = from([
{ name: 'Joe', age: 30 },
{ name: 'Frank', age: 20 },
{ name: 'Ryan', age: 50 }
]);
// 提取每个 person 的 name 属性
const example = source.pipe(map(({ name }) => name));
// 输出: "Joe","Frank","Ryan"
const subscribe = example.subscribe(val => console.log(val));
相关食谱
其他资源
- map - 官方文档
- map vs flatMap - Ben Lesh
- 转换操作符: map 和 mapTo - André Staltz
源码: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/map.ts