【问题标题】:Observable.create(...).map is not a functionObservable.create(...).map 不是函数
【发布时间】:2018-11-13 08:07:28
【问题描述】:

我刚刚学习了 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')
);

【问题讨论】:

  • Observable.create() 返回一个Observable,而不是一个数组。
  • 在 v6 中,您需要使用 pipable 操作符,或者需要在 rxjs 旁边安装 rxjs-compat。请参阅migration guide。此外,使用new Observable 优于使用Observable.create

标签: javascript typescript rxjs


【解决方案1】:

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

您的代码已编辑:

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

【讨论】:

  • 在 angular/typescript 和 RxJs 6+ 中,您必须调用 map 函数的通用版本。地图(n => n * 2)
  • 对不起,我不明白你试图解释什么,我的样本有什么可以改进的?
  • 谢谢你们两个。 @Yanis-git 请更新您的答案,在 map 之后添加 。没有它会产生错误:[ts] 算术运算的左侧必须是“任意”、“数字”或枚举类型。
【解决方案2】:

我正在做同样的课程,并且能够使用管道并通过以下方式在箭头函数的参数中键入变量来解决这个问题:

...
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)
);
...

要求在管道内使用操作符是 RxJs 工作方式的最新变化,因此某些课程和参考资料可能已过时。

【讨论】:

  • 欢迎来到 StackOverflow。虽然此代码可能会回答问题,但提供有关此代码为何和/或如何回答问题的额外上下文可提高其长期价值。
猜你喜欢
  • 2019-03-25
  • 2016-09-02
  • 2015-10-18
  • 2021-12-03
  • 2020-08-13
  • 2018-06-21
  • 2020-08-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多