網站搜尋

typescript - 當使用者跳轉到不同頁面時,setTimeout 繼續運行,如何在 Angular TypeScript 中清除 setTimeout?


我使用 setTimeout 在 10 秒後跳轉到上傳頁面。但是當使用者導航到其他頁面時,超時仍然會繼續。我按照這個連結上的說明(Angular 2 setinterval() 在其他組件上仍然運行)並在 ngOnDestroy 中添加了 clearTimeout,但它不起作用。

  ngOnInit() {
    
    // Get uploaded file info
    this.uploadService.getFileInfo().subscribe((value) => {
      this.fileInfo = value;
    

      this.http.post(environment.apiUrl+'/api/dataValidation/validateData.php', this.fileInfo)
        .subscribe(res => {
          console.log('response'+res)
          if (res['length']<5) {
            
            //console.log(res);
            this.failure = true;
            this.fileValidationResults.errorMessage =res[0];
            this.loading = false; // stop loading screen
            this._timer =setTimeout(() => {
              this.router.navigate(["/uploads/upload"]);
            }, 10000); 
          }
        })
    });

  }
  ngOnDestroy() {
    if (this._timer){
      clearTimeout(this._timer);
  };
  }

當使用者導航到其他連結時,我如何停止 setTimeout(),並讓 setTimeout() 只在它自己的組件中運行?

答案#1

應該可行,記得在宣告你的元件實作 OnDestroy 時

順便說一下,你可以使用 rxjs 的 timer 運算子來取代 setTimeout

import {timer} from 'rxjs'
import {takeWhile} from 'rxjs/operators'
...

export class OneComponent implements OnInit,OnDestroy {

   alive:boolean=true;

   ngOnInit(){    
     timer(1000).pipe(takeWhile(()=>this.alive)).subscribe(_=>{
        this.router.navigate(['/three'])
     })
   }

   ngOnDestroy()
   {
       this.alive=false;
   }
}