如何在 Angular 中满足条件时运行和停止订阅中的间隔方法

Mad*_*pop 1 javascript rxjs angular angular-httpclient

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

下面是我的代码

主要订阅方式

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

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

})
Run Code Online (Sandbox Code Playgroud)

间隔法:

getInterval(){
  this.authservice.getIntervalData().subscribe(resp => {
    console.log(resp)
   this.responseStatus = resp
  })
}
Run Code Online (Sandbox Code Playgroud)

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

继续

停止

终止

因此,在这里我需要在 Main 订阅方法中调用 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( <第一个响应参数> ).pipe( map(data => [data, t]))) takeWhile(([data, t]) => data !== 'TERMINATE' && t < 12), map (([data, t]) => data) )) ).subscribe(data => console.log(data))

bry*_*n60 5

你可能只想使用运算符和可观察量......

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))
Run Code Online (Sandbox Code Playgroud)

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