mapTo

signature: mapTo(value: any): Observable

Map emissions to constant value.

mapTo - 图1

Examples

Example 1: Map every emission to string

( StackBlitz |
jsBin |
jsFiddle )

  1. import { interval } from 'rxjs/observable/interval';
  2. import { mapTo } from 'rxjs/operators';
  3. //emit value every two seconds
  4. const source = interval(2000);
  5. //map all emissions to one value
  6. const example = source.pipe(mapTo('HELLO WORLD!'));
  7. //output: 'HELLO WORLD!'...'HELLO WORLD!'...'HELLO WORLD!'...
  8. const subscribe = example.subscribe(val => console.log(val));
Example 2: Mapping clicks to string

( StackBlitz |
jsBin |
jsFiddle )

  1. import { fromEvent } from 'rxjs/observable/fromEvent';
  2. import { mapTo } from 'rxjs/operators';
  3. //emit every click on document
  4. const source = fromEvent(document, 'click');
  5. //map all emissions to one value
  6. const example = source.pipe(mapTo('GOODBYE WORLD!'));
  7. //output: (click)'GOODBYE WORLD!'...
  8. const subscribe = example.subscribe(val => console.log(val));

Additional Resources


:file_folder: Source Code:
https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/mapTo.ts