Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - RxJS Switch Map Issue

I'm trying to have an infinite scrolling section in my application. To achieve this I'm using this component to handle the scroll events and so on. When the scroll reaches the bottom of the div I'm calling a function to get more data. So far so good.

To make this function more efficient I'm trying to wait a few seconds before the call is made as well as make sure that the data is processed properly. To do this I've been looking at the example shown on the Angular website that showcases a wikipedia search.

I have a similar setup to what is being shown in the article, my problem is that I'm getting the following error when I call switchMap():

Type 'void' is not assignable to type 'ObservableInput<{}>'

This is a sample of my code:

private scrollEndActive: Subject<boolean> = new Subject<boolean>();

ngOnInit() {
    ...
    this.scrollEndActive
        .debounceTime(1000)
        .distinctUntilChanged()
        .switchMap(data => {
            // ... get data from server
        })
}

...

// event to trigger call to server
scrollEnd() {
    this.scrollEndActive.next(true);
}

With the code above this is what I'm getting:enter image description here

From the research I've made it seems to be an issue related to the fact that one should return the Observable (Type 'void' is not assignable to type 'ObservableInput<{}>'). But in my case I'm not sure what is the issue.

I'm working with:

  • Angular 4.0.1
  • TypeScript 2.2.2
  • RxJS 5.2.0
like image 377
Daniel Grima Avatar asked May 18 '17 09:05

Daniel Grima


1 Answers

By default, an arrow function () => {...} has the return type void unless you return something.

If you want to use switchMap to return nothing, you can do as yurzui said in the comments, return Observable.empty().

That being said, if you return an observable of null in your switchMap, it means that you don't need switchMap and you can directly use do operator, that doesn an action without modifying returned data. Or mergeMap that allows you to return a new Observable from the data you got from the original one.

like image 145
Supamiu Avatar answered Nov 15 '22 04:11

Supamiu