Angular setTimeout 运行 次数太多

Angular setTimeout running too many times

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

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

下面是创建 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);
    }
}

要解决这个问题 Angular 有 Singleton services。您可以在 LogsService.

中移动 setLogTimer()logTimer

问题是 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()