首页 > 解决方案 > 如果在Angular中满足条件,如何在订阅中运行和停止间隔方法

问题描述

在这里我有一个疑问,我如何在订阅中调用间隔方法并在满足条件后停止它

下面是我的代码

主要订阅方法

this.authservice.getdata().subscribe(response => {
   console.log(res)

   // Polling method
    
    SetInterval(()=>{
     this.getInterval();
   },5000)

})

间隔法:

getInterval(){
  this.authservice.getIntervalData().subscribe(resp => {
    console.log(resp)
   this.responseStatus = resp
  })
}

在响应中,它给出了 3 种类型的响应

继续

停止

终止

所以在这里我需要在 Main subscribe 方法中调用 getInterval() ,直到 GetInterval 给我 Proceed 作为响应或者直到轮询后 1 分钟我设置了运行间隔,如果满足其中任何一个条件,我必须停止轮询。

注意:如果主订阅对成功做出响应,我不需要轮询主订阅方法,那么只有我开始这个轮询

更新: 以下方法有效,但在这里我需要两件事

  1. 如何设置变量并将响应存储在其中

  2. 如果响应来了,我如何根据 res 设置布尔变量

    this.content =true 同样明智

    因为当我尝试在 switchMap 中设置变量时,它不接受

    this.authservice.getdata().pipe( switchMap(resp => timer(0, 5000).pipe( // 需要将此响应存储在全局变量中,以便进一步使用 switchMap(t => this.authservice) .getIntervalData( <1st response param> ).pipe( map(data => [data, t]))) takeWhile(([data, t]) => data !== 'TERMINATE' && t < 12), map (([data, t]) => data) )) ).subscribe(data => console.log(data))

标签: javascriptangularrxjsangular-httpclient

解决方案


您可能只想使用运算符和可观察对象....

this.authservice.getdata().pipe( // get initial data
  tap(resp => this.myVariable = resp),
  switchMap(resp => timer(0, 5000).pipe( // switch to timer that emits every 5 seconds
    switchMap(t => this.authservice.getIntervalData().pipe( // swtich again to interval data
      map(data => [data, t]))) // map to response and timer value
    takeWhile(([data, t]) => data !== 'TERMINATE' && t < 12), // whatever stop condition, this says stop when the data is terminate or the timer has emitted 12 times (1 minute if emitting every 5 seconds)
    map(([data, t]) => data) // just send the data through
  ))
).subscribe(data => console.log(data))

类似的事情就是我将如何实现这一点。


推荐阅读