Wang Liang
Wang Liang

Reputation: 4434

Error: You provided 'null' where a stream was expected

I am first in rxjs, and below code is working, and no problem with usage as users.

this.searchField.valueChanges.pipe(
      debounceTime(1000),
      switchMap(searchText => {
        if (searchText .length >= 3) {
          return this.api.post(`api/medicine/medicines`, { product: searchText })
        }
        else {
          return null; // this is make errors
        }
      })
    ).subscribe(term => {
      console.log('api: ', term)
      this.MedicineList = term;
      this.onChangeText();
    });

This is working on my side, but i can see errors.

Error screen

I want to remove this error log.

Upvotes: 0

Views: 1442

Answers (4)

Wang Liang
Wang Liang

Reputation: 4434

this.searchField.valueChanges.pipe(
      debounceTime(1000),
      switchMap(searchText => {
        if (searchText .length >= 3) {
          return this.api.post(`api/medicine/medicines`, { product: searchText })
        }
        else {
          return []; // <-----------------
        }
      })
    ).subscribe(term => {
      console.log('api: ', term)
      this.MedicineList = term;
      this.onChangeText();
    });

Upvotes: 0

bjdose
bjdose

Reputation: 1309

The error shown in your console says "You provided 'null' where a stream was expected. You can provide an Observable, promise, Array or Iterable". That error is really descriptive. This way you're returning null in your if block, in order to fix your issue you need to provide an Observable. Depends on what you need you can adopt the real solution.

A simple way to fix this is returning an observable (empty(), never(), of(), etc).

import {
  empty
} from 'rxjs';

this.searchField.valueChanges.pipe(
      debounceTime(1000),
      switchMap(searchText => {
        if (searchText .length >= 3) {
          return this.api.post(`api/medicine/medicines`, { product: searchText })
        }
        else {
          return empty(); // <- You don't call next with empty
        }
      })
    ).subscribe(term => {
      console.log('api: ', term)
      this.MedicineList = term;
      this.onChangeText();
    });

You can learn more about rxjs here: RxJS Empty Docs

Upvotes: 3

Jonathan Stellwag
Jonathan Stellwag

Reputation: 4267

In switchMaps you handle streams. The documentaiton says: "switch to a new observable". This is why you cannot return a single value. Instead you need to return an observable with the value null.

of(null)

Upvotes: 2

Johnathan DiMatteo
Johnathan DiMatteo

Reputation: 51

use of(null) to convert the null to an observable. switchMap has to return an observable.

Upvotes: 3

Related Questions