Angular setTimeout运行太多次

问题描述 投票:0回答:2

我有一个由两个或多个其他组件实现的日志查看器组件。该日志查看器使用setTimeout创建一个间隔循环以从文件中获取数据。我的问题是,由于此组件已导入其他组件中,因此计时器会分别为每个组件运行计时器,从而每秒读取多个文件。

可以避免这种情况,并且无论使用该组件的组件数量如何,都只运行一次计时器?

这是在其中创建setTimeout间隔的日志查看器组件的代码:

import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { LogsService } from '../../services/logs.service';
import { HelperService } from '../../services/helper.service';

@Component({
    selector: 'app-logger',
    templateUrl: './logger.component.html',
    styleUrls: ['./logger.component.scss']
})
export class LoggerComponent implements OnInit {
    @ViewChild('scroller', {static: false}) scroller: ElementRef;

    logClassName: string = 'logs shadow close';
    logs: string = '';
    logTS: number = 0;
    logTimer;
    scrollTop: number = 0;

    constructor(
        private logsService: LogsService,
        private h: HelperService
    ){}

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

    ngOnDestroy(): void {
        if (this.logTimer) window.clearTimeout(this.logTimer);
    }

    toggle(type){
        switch (type)
        {
            case 'open': this.logClassName = 'logs shadow open'; break;
            case 'close': this.logClassName = 'logs shadow close'; break;
            case 'full': this.logClassName = 'logs shadow full'; break;
        }
    }

    getLogs(){
        this.logsService.fetch(this.logTS).subscribe(
            response => {
                this.logs += response.data.join('');
                this.logTS = response.ts;

                window.setTimeout(() => {
                    this.scrollTop = this.scroller.nativeElement.scrollHeight;
                }, 100);

                this.setLogTimer();
            },
            error => {
                this.h.lg('unable to fetch logs', 'error');
                this.logs = '<p>Unable to fetch logs</p>';

                this.setLogTimer();
            }
        );
    }

    setLogTimer(){
        if (this.logTimer) window.clearTimeout(this.logTimer);

        this.logTimer = window.setTimeout(() => {
            this.getLogs();
        }, 1000);
    }
}
javascript angular intervals
2个回答
0
投票

为了解决此问题,Angular具有Singleton services


0
投票

问题是this.logTimer与组件实例相关联,并且每个实例都不同,并且永远不会被取消的解决方案是使用某些共享服务来执行文件读取,如[]]

@Injectable(provideIn:'root')
export class SomeService{

    setLogTimer(){
            if (this.logTimer) window.clearTimeout(this.logTimer);

            this.logTimer = window.setTimeout(() => {
                this.getLogs();
            }, 1000);
        }

}

然后在组件中使用此服务,例如

this.someService.setLogTimer()
© www.soinside.com 2019 - 2024. All rights reserved.