【问题标题】:Error: You provided 'null' where a stream was expected错误:您在预期流的位置提供了“null”
【发布时间】:2020-06-16 02:59:18
【问题描述】:

我是rxjs的第一人,下面的代码是可以工作的,作为用户使用没有问题。

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();
    });

这对我有用,但我可以看到错误。

我想删除这个错误日志。

【问题讨论】:

  • 错误中描述了所有内容。 SwitchMap 应该返回流而不是 null。
  • 是的,但是,我怎样才能返回空流而不是 null?
  • 请发给我例子
  • i.stack.imgur.com/mYWHc.png尝试过滤流,这样就不用切换流了,learnrxjs.io/learn-rxjs/operators/filtering/filter

标签: javascript angular rxjs


【解决方案1】:

使用 of(null) 将 null 转换为 observable。 switchMap 必须返回一个 observable。

【讨论】:

    【解决方案2】:

    switchMaps 中,您处理流。文档说:“切换到新的 observable”。这就是为什么您不能返回单个值的原因。相反,您需要返回一个值为 null 的 observable。

    of(null)
    

    【讨论】:

      【解决方案3】:

      控制台中显示的错误是“您在预期流的位置提供了 'null'。您可以提供 Observable、promise、Array 或 Iterable”。该错误确实具有描述性。这样,您将在 if 块中返回 null,为了解决您的问题,您需要提供一个 Observable。取决于您需要什么,您可以采用真正的解决方案。

      解决此问题的一种简单方法是返回一个可观察对象(empty()、never()、of() 等)。

      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();
          });
      

      您可以在此处了解有关 rxjs 的更多信息:RxJS Empty Docs

      【讨论】:

        【解决方案4】:
        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();
            });
        

        【讨论】:

          猜你喜欢
          • 2021-05-21
          • 2020-03-10
          • 2021-11-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-05-31
          • 2021-09-10
          • 2022-01-17
          相关资源
          最近更新 更多