簡體   English   中英

如果條件在Angular中滿足,如何在訂閱中運行和停止間隔方法

[英]How to run and stop the interval method in the subscribe if condition is met in 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))

您可能只想使用運算符和可觀察對象....

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))

類似的事情就是我將如何實現這一點。

考慮實現它,如下所示:

this.authservice.getdata().pipe(
  tap(x => this.globalVariable = x),
  switchMap(data => interval(5000).pipe(
    switchMap(x => this.authservice.getIntervalData(x)), //<== pass data from first subscription to second
    takeUntil(timer(60 * 1000)),
    takeWhile(x => x !== 'TERMINATE'),
    map(data2 => [data, data2]) // <= return values from both subscriptions 
  ))

更新:

“在方法之外停止這個間隔,我的意思是點擊按鈕”

clicked$ = new Subject<void>();

onclick(){
  this.clicked.next(); // on click emit value
}


this.authservice.getdata().pipe(
  tap(x => this.globalVariable = x),
  switchMap(data => interval(5000).pipe(
    switchMap(x => this.authservice.getIntervalData(x)), //<== pass data from first subscription to second
    takeUntil(timer(60 * 1000)),
    takeWhile(x => x !== 'TERMINATE'),
    map(intervalDataRes => this.condition = intervalDataRes),
    takeUntil(merge(this.clicked$, timer(2 * 60 * 1000))) // interval will stop after 2 or as soon as clicked$ emits
  ))

考慮使用Subject來存儲全局變量。 這樣你就可以完全避免訂閱

以下解決方案已在 stackblitz 上進行測試,請參閱此鏈接

  // Emit Once after 60 Seconds
  stopTime$ = timer(60000);

  // TerminateResponse
  terminateSubject$ = new Subject();
  terminateAction$ = this.terminateSubject$.asObservable();

  // Emits Every 5 seconds until stopTime is called
  interval$ = timer(0, 5000).pipe(
    takeUntil(this.stopTime$),
    takeUntil(this.terminateAction$),
  );

  // Global Variable
  responseSubject$ = new Subject()
  responseAction$ = this.responseSubject$.asObservable();

  // Create Interval Observable. This will call getIntervalData until no more interval
  intervalData$ = this.interval$.pipe(
    switchMap(() => this.authservice.getIntervalData()),
    tap(res => this.responseSubject$.next({res, content: true})),
    tap(res => res === 'Terminate' ? this.terminateSubject$.next(true): ''),
  
  )

我們定義一個變量

stopTime$ = timer(60000);

這在 60000 毫秒后發出一次,即 1 分鍾

接下來我們定義

 terminateSubject$ = new Subject();
 terminateAction$ = this.terminateSubject$.asObservable();

當條件滿足時,我們將使用這個 observable 來終止計時器,使用takeUntil操作符並調用 observable 上的next()函數

然后我們定義

interval$ = timer(0, 5000).pipe(
    takeUntil(this.stopTime$),
    takeUntil(this.terminateAction$),
  );

此 observable 將每 5000 毫秒發出 0 延遲,直到調用stopTime$ observable 或調用terminateAction$

然后我們創建一個主題來存儲我們的全局變量。 由於 observables 是異步的,為了避免未定義值,使用 observables 來存儲我們的變量並在我們需要時訂閱這些變量是有意義的

  responseSubject$ = new Subject()
  responseAction$ = this.responseSubject$.asObservable();

最后我們定義我們的區間 Data Observable

  intervalData$ = this.interval$.pipe(
    switchMap(() => this.authservice.getIntervalData()),
    tap(res => this.responseSubject$.next({res, content: true})),
    tap(res => res === 'Terminate' ? this.terminateSubject$.next(true): ''),

  )

tap(res => this.responseSubject$.next({res, content: true}))存儲全局變量tap(res => res === 'Terminate' ? this.terminateSubject$.next(true): '')終止可觀察的區間

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM