Observable.create(...)。map不是函数

时间:2018-06-04 03:03:16

标签: javascript typescript rxjs

我只是学习Pluralsight - 使用RxJS开始反应式编程

为什么不工作?

我使用RXJS 6.2.0

import {Observable} from 'rxjs';

const numbers = [1, 5, 10];
const source = Observable.create(observer => {

  let index = 0;
  let produceValue = () => {
    observer.next(numbers[index++]);

    if (index < numbers.length) {
      setTimeout(produceValue, 2000);
    } else {
      observer.complete();
    }
  };

  produceValue();

}).map(n => n * 2)
  .filter(n => n > 4);

source.subscribe(
  value => console.log(`value: ${value}`),
  e => console.log(`error: ${e}`),
  () => console.log('complete')
);

2 个答案:

答案 0 :(得分:5)

我也在做同样的过程,并且能够通过管道并在箭头函数的参数中键入变量来解决此问题,方法如下:

...
let source = Observable.create(observer => {

    let index = 0;
    let produceValue = () => {

        observer.next(numbers[index++]);

        if (index < numbers.length) {
            setTimeout(produceValue, 250);
        } else {
            observer.complete();
        }
    }

    produceValue();
}).pipe(
    map((n: number) => n * 2),
    filter((n: number) => n > 4)
);
...

要求在管道内部使用运算符是RxJ的工作方式的最新更改,因此某些课程和参考资料可能已过时。

答案 1 :(得分:2)

根据评论建议,您现在应该使用管道。

您的代码已编辑:

import {Observable} from 'rxjs';
import {map, filter} from 'rxjs/operators';
const numbers = [1, 5, 10];
const source = Observable.create(observer => {

  let index = 0;
  let produceValue = () => {
    observer.next(numbers[index++]);

    if (index < numbers.length) {
      setTimeout(produceValue, 2000);
    } else {
      observer.complete();
    }
  };

  produceValue();

}).pipe(map<number, number>(n => n * 2),filter(n => n > 4)); // Here we pipe operators, you can provide any number of operators. or chain many pipe. 

source.subscribe(
  value => console.log(`value: ${value}`),
  e => console.log(`error: ${e}`),
  () => console.log('complete')
);

online sample