RxJS: How to do some clean-up before reactive search in angular 2

463 views Asked by At

Here is my scenario

I want to reactive search if the value length > 2 do api search else clear data.

But I don't know to clear data

userList: Observable<User[]>; 

The userList should be empty when length <= 2

The other question is why Rxjs do operator not work in angular 2?

this.userList = this.userNameCtrl.valueChanges.do(d => console.log(d));

Here is my code:

this.userList = this.userNameCtrl.valueChanges
            .filter(x => x.length > 2)
            .debounceTime(400)
            .distinctUntilChanged()
            .switchMap(value => this._userService.searchUsers(value));
1

There are 1 answers

1
Sergey Sokolov On BEST ANSWER

I want to reactive search if the value length > 2 do api search else clear data.

If I understood right by clearing you mean pushing empty array down to stream:

this.userList = this.userNameCtrl.valueChanges
    .debounceTime(400)
    .distinctUntilChanged()
    .switchMap(value => {
        if(value.length > 2) {
            return this._userService.searchUsers(value);
        } else {
            return Observable.of([]);
        }
    });

The other question is why Rxjs do operator not work in angular 2?

this.userList = this.userNameCtrl.valueChanges.do(d => console.log(d));

This code doesn't output anything because you need to subscribe to observable first

this.userList = this.userNameCtrl.valueChanges
    .do(d => console.log(d))
    subscribe(() => {});

// or simply

this.userList = this.userNameCtrl.valueChanges
    subscribe(d => console.log(d));