map

签名: map(project: Function, thisArg: any): Observable

对源 observable 的每个值应用投射函数。

map - 图1

示例

示例 1: 每个数字加10

( StackBlitz |
jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. import { map } from 'rxjs/operators';
  3. // 发出 (1,2,3,4,5)
  4. const source = from([1, 2, 3, 4, 5]);
  5. // 每个数字加10
  6. const example = source.pipe(map(val => val + 10));
  7. // 输出: 11,12,13,14,15
  8. const subscribe = example.subscribe(val => console.log(val));
示例 2: 映射成单一属性

( StackBlitz |
jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. import { map } from 'rxjs/operators';
  3. // 发出 ({name: 'Joe', age: 30}, {name: 'Frank', age: 20},{name: 'Ryan', age: 50})
  4. const source = from([
  5. { name: 'Joe', age: 30 },
  6. { name: 'Frank', age: 20 },
  7. { name: 'Ryan', age: 50 }
  8. ]);
  9. // 提取每个 person 的 name 属性
  10. const example = source.pipe(map(({ name }) => name));
  11. // 输出: "Joe","Frank","Ryan"
  12. const subscribe = example.subscribe(val => console.log(val));

相关食谱

其他资源


:file_folder: 源码: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/map.ts