from

签名: from(ish: ObservableInput, mapFn: function, thisArg: any, scheduler: Scheduler): Observable

将数组、promise 或迭代器转换成 observable 。


:bulb: 对于数组和迭代器,所有包含的值都会被作为序列发出!

:bulb: 此操作符也可以用来将字符串作为字符的序列发出!


from - 图3

示例

示例 1: 数组转换而来的 observable

( jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. // 将数组作为值的序列发出
  3. const arraySource = from([1, 2, 3, 4, 5]);
  4. // 输出: 1,2,3,4,5
  5. const subscribe = arraySource.subscribe(val => console.log(val));
示例 2: promise 转换而来的 observable

( jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. // 发出 promise 的结果
  3. const promiseSource = from(new Promise(resolve => resolve('Hello World!')));
  4. // 输出: 'Hello World'
  5. const subscribe = promiseSource.subscribe(val => console.log(val));
示例 3: 集合转换而来的 observable

( jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. // 使用 js 的集合
  3. const map = new Map();
  4. map.set(1, 'Hi');
  5. map.set(2, 'Bye');
  6. const mapSource = from(map);
  7. // 输出: [1, 'Hi'], [2, 'Bye']
  8. const subscribe = mapSource.subscribe(val => console.log(val));
示例 4: 字符串转换而来的 observable

( jsBin |
jsFiddle )

  1. import { from } from 'rxjs/observable/from';
  2. // 将字符串作为字符序列发出
  3. const source = from('Hello World');
  4. // 输出: 'H','e','l','l','o',' ','W','o','r','l','d'
  5. const subscribe = source.subscribe(val => console.log(val));

相关食谱

其他资源


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