简体   繁体   English

如何使用angular2在组件初始化上运行一次间隔?

[英]How to run an interval on component init only once with angular2?

I have an interval launched in my component: 我在组件中启动了一个间隔:

export class FoobarComponent implements OnInit {

    ngOnInit(): void {
        this.startInterval();
    }

    startInterval() void {
        setInterval(() => { console.log('Hi'); }, 1000);
    }    
}

Each time the component is called, a new interval is created in addition to the previous ones. 每次调用该组件时,除了先前的间隔外,还会创建一个新的间隔。

I tried to used an ID (as I used to do with plain JS before) with something like: 我试图使用一个ID(就像我以前使用纯JS一样):

export class FoobarComponent implements OnInit {

    intervalId: Number;

    ngOnInit(): void {
        this.startInterval();
    }

    startInterval() void {
        if(this.intervalId) { // always undefined 
            window.clearInterval(this.intervalId);
        }
        this.intervalId = window.setInterval(() => { console.log('Hi'); }, 1000);
    }
}

But it's not working since intervalId became undefined each time the component is called. 但这是行不通的,因为每次调用该组件时都未定义intervalId So the previous intervals keep running while a new one is created. 因此,在创建新间隔之前,先前的间隔将继续运行。

I don't know how to stop an interval already running. 我不知道如何停止已经运行的间隔。 Could you help me to do it? 你能帮我做吗?

You can make the intervalID static. 您可以将intervalID设为静态。 That way all class instances will be able to access the same one. 这样,所有类实例都将能够访问同一实例。

export class FoobarComponent implements OnInit {

    static intervalId: Number;

    ngOnInit(): void {
        this.startInterval();
    }

    startInterval() void {
        if(FoobarComponent.intervalId) { // always undefined 
            window.clearInterval(this.intervalId);
        }
        FoobarComponent.intervalId = window.setInterval(() => { console.log('Hi'); }, 1000);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM