首页 > 解决方案 > rxjs,switchMap,interval,在预期流的地方提供了“未定义”

问题描述

试图从服务器获取数据,每隔 10 秒间隔一次服务。如果返回价格,则停止间隔。下面的代码:

但我收到错误:

错误类型错误:您在预期流的位置提供了“未定义”。您可以提供 Observable、Promise、Array 或 Iterable。

代码:

public Respond() {

this.dataService.WaitingForServiceRespond()
  .pipe((
    debounceTime(2000),
    switchMap((r: any) => {
      if (!r.price) {
        setInterval(() => {
          return this.Respond();
        }, 10000)
      } else {

        this.dataService.user.payment = r;
        console.log('price returned', r);
        return ''
      }
    })
  ))
  .subscribe(e => {
    console.log(e)
  })

}

标签: angularrxjsrxjs6

解决方案


问题出在你的switchMap. 它期望返回一个流。你使用时什么也不返回setInterval。您可以Observable通过返回interval()rxjs不是调用来返回一个setInterval()

import { interval } from 'rxjs';
...

public Respond() {

this.dataService.WaitingForServiceRespond()
  .pipe((
    debounceTime(2000),
    switchMap((r: any) => {
      if (!r.price) {

        return interval(10000).pipe(tap(() => this.Respond()))

      } else {

        this.dataService.user.payment = r;
        console.log('price returned', r);
        return of('')
      }
    })
  ))
  .subscribe(e => {
    console.log(e)
  })
}

推荐阅读