简体   繁体   中英

Observable.create(…).map is not a function

I just learn Pluralsight - Getting Started with Reactive Programming with RxJS

Why not work?

I use 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')
);

I was doing the same course and was able to solve this using pipe and typing the variable in the parameters of the arrow functions, in the following way:

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

Requiring using operators inside of pipe is a recent change on the way RxJs works, so some courses and references may be out of date.

as recommended on comment, you should use pipe now.

Your code edited :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM