【发布时间】:2020-10-07 14:30:46
【问题描述】:
我正在尝试使用角度服务在一组组件中设置超时。我试图按照我在网上找到的材料进行操作,但我有点卡住了。我已经创建了 timeout.service.ts 文件并将代码放在那里,但出现了多个错误。我需要帮助才能做到这一点。超时在组件本身中工作正常,但我想根据 DRY 方法工作。感谢您对解决此问题的支持!
堆栈闪电战:https://stackblitz.com/edit/flight-date-picker-with-service
组件.TS:
import { Component, OnInit } from '@angular/core';7
import { Router, RouterLink } from '@angular/router';
import { HostListener } from '@angular/core'
import { TimeoutService } from '../timeout.service';
@Component({
selector: 'app-chooseflight',
templateUrl: './chooseflight.component.html',
styleUrls: ['./chooseflight.component.scss'],
providers: [TimeoutService]
})
export class ChooseflightComponent implements OnInit {
constructor(private router: Router, timeoutService: TimeoutService) {
this.showStorage = localStorage.getItem("flightdetails") || {};
}
ngOnInit() {
this.resetTimer();
}
// public time: any;
// @HostListener('document:mousemove')
// @HostListener('document:keypress')
// @HostListener('document:click')
// @HostListener('document:wheel')
// resetTimer() {
// clearTimeout(this.time);
// this.time = setTimeout(() => {
// localStorage.removeItem("flightdetails");
// console.log("Local storage will now be deleted");
// this.router.navigate(["/chooseflight"]);
// }, 180000);
// }
注释部分已移至服务文件:
export class TimeoutService {
public time: number;
console.log("TimeoutService Działa!");
@HostListener('document:mousemove')
@HostListener('document:keypress')
@HostListener('document:click')
@HostListener('document:wheel')
resetTimer() {
clearTimeout(this.time);
this.time = setTimeout(() => {
localStorage.removeItem("flightdetails");
console.log("Local storage will now be deleted");
this.router.navigate(["/chooseflight"]);
}, 180000);
}
}
【问题讨论】:
标签: angular service components