【问题标题】:Check current component after timeout超时后检查当前组件
【发布时间】:2018-06-07 09:59:02
【问题描述】:

我在一个名为“recoger_success”的组件中,我希望它在单击链接了 countdown() 的按钮后 10 秒后导航到主组件。问题是,如果我在超时达到 0 之前导航到另一个组件,那么在 10 秒之后,我在哪个组件中并不重要,它总是会转到主组件。我不希望它只在用户仍在超时组件上时转到主组件,否则忽略它..

我试过这个来知道实际组件的 url,但它不起作用..

countdown(){
  setTimeout(() => {
    if (this.route.snapshot.url.toString() == 'recoger_success'){
        this.router.navigate([""]);
    }
  }, 10000);

}

感谢任何帮助。

【问题讨论】:

    标签: html angular routes timeout angular-activatedroute


    【解决方案1】:

    将超时分配给变量,并在您手动存在页面时清除超时

    countdown(){
      this.timeout = setTimeout(() => {
        if (this.route.snapshot.url.toString() == 'recoger_success'){
            this.router.navigate([""]);
        }
      }, 10000);
    }
    
    function myStopFunction() {
        clearTimeout(this.timeout);
    }
    

    【讨论】:

    • 我觉得这不是完美的方法,但如果我将它与订阅一起使用以了解路由是否更改然后使用 mystopfunction router.events.subscribe((val) = > { this.myStopFunction(); });
    【解决方案2】:

    您需要将 setTimeout 绑定到一个变量。

    component.ts

    import { Component, OnDestroy } from '@angular/core';
    
    export class Component implements OnDestroy {
    
      countdownTimer: any;
    
      countdown() {
        if (this.countdownTimer) {
          clearInterval(this.countdownTimer);
        }
        this.countdownTimer = setTimeout(() => {
          if (this.route.snapshot.url.toString() == 'recoger_success') {
            this.router.navigate([""]);
          }
        }, 10000);
      }
    
    
      ngOnDestroy() {
        if (this.countdownTimer) {
          clearInterval(this.countdownTimer);
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多