rxjs,switchMap,interval,提供'undefined',其中包含一个流

问题描述 投票:0回答:1

尝试从服务器获取数据,间隔为服务每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)
  })

}

angular rxjs rxjs6
1个回答
1
投票

问题出在你的switchMap上。它希望返回一个流。当你使用setInterval时,你什么都不返回。你可以通过返回Observableinterval()而不是调用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)
  })
}
© www.soinside.com 2019 - 2024. All rights reserved.