当用户路由到不同的页面时,setTimeout 继续,如何在 angular 打字稿中清除超时?
setTimeout continues when user route to different page, how to clearTimeout in angular typscript?
我用setTimeout 10秒后跳转到上传页面。但是当用户导航到另一个页面时超时继续。我按照 link() 上的说明将 clearTimeout 添加到 ngOnDestroy,但它不起作用。
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);
};
}
当用户导航到另一个 link 并让 setTimeout() 仅在它自己的组件中工作时,如何停止 setTimeout()?
应该 工作,记住当声明你的组件实现 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;
}
}
我用setTimeout 10秒后跳转到上传页面。但是当用户导航到另一个页面时超时继续。我按照 link(
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);
};
}
当用户导航到另一个 link 并让 setTimeout() 仅在它自己的组件中工作时,如何停止 setTimeout()?
应该 工作,记住当声明你的组件实现 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;
}
}