rxjs flatmap missing

断了今生、忘了曾经 提交于 2019-11-28 22:17:10
Georg Heiler

It turns out the answer is quite simple:

the operator is called mergeMap in this version of rxjs

EDIT:

Furthermore, you might have to use import 'rxjs/add/operator/mergeMap'.

Chris Peacock

In my case I needed to import the augmentation for mergeMap:

import 'rxjs/add/operator/mergeMap';

As flatMap is an alias of mergeMap, importing the module above will enable you to use flatMap.

With RxJS 5.5+, the flatMap operator has been renamed to mergeMap. Instead, you should now use the mergeMap operator in conjunction with pipe.

You can still use flatMap using the alias FlatMap.

RxJS v5.5.2 is the default dependency version for Angular 5.

For each RxJS Operator you import, including mergeMap, you should now import from 'rxjs/operators' and use the pipe operator.

Example of using mergeMap on an Http request Observable

import { Observable } from 'rxjs/Observable';
import { catchError } from 'rxjs/operators';
...

export class ExampleClass {
  constructor(private http: HttpClient) {
    this.http.get('/api/words').pipe(
      mergeMap(word => Observable.of(word.join(' '))
    );
  }
  ...
}

Notice here that flatMap is replaced with mergeMap and the pipe operator is used to compose the operators in similar manner to what you're used to with dot-chaining.


See the rxjs documentation on lettable operators for more info https://github.com/ReactiveX/rxjs/blob/master/doc/lettable-operators.md

Correct import should look like below:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/mergeMap';

Importing the module mergeMap will enable you to use flatMap in your code

When you will import in your code import { Observable } from 'rxjs/Rx';, additional mergeMap import is not needed but you can expect errors during the AoT compilation.

ERROR in ./node_modules/rxjs/_esm5/observable/BoundCallbackObservable.js
Module build failed: TypeError: Cannot read property 'type' of undefined

Quick Update - May 2019

Using rxjs v6.5.1

Import as a mergeMap operator, eg/

import { Observable, from, of } from "rxjs";
import { map, filter, mergeMap } from "rxjs/operators";

Then use in conjunction with the new pipe feature, eg/

var requestStream = of("https://api.github.com/users");
var responseStream = requestStream.pipe(
  mergeMap(requestUrl => {
    console.log(requestUrl);
    ... // other logic
    return rp(options);  // returns promise
  })
);
Karfann Nacif

It worked for me!

import { Observable } from 'rxjs/Rx';
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!