英文:
How to execute angular function one time and leave it also after reload component
问题
我正在学习Angular并面临以下问题 - 如果我理解正确 - 我在ngOnInit
中放入的所有内容都会在每次组件重新加载时执行。我有一个定时器函数,需要在页面重新加载时继续运行,而不是重新开始计数。我如何在ngOnInit
之外或HTML中执行startTimer(secsToStart: number)
函数,或者是否有其他Angular功能我需要查看。
组件代码:
@Component({
selector: 'app-task-countdown',
templateUrl: './task-countdown.component.html',
styleUrls: ['./task-countdown.component.css'],
})
export class TaskCountdownComponent implements OnInit {
@Input()
tasks!: Tasks[];
excuse!: Loosers[];
excuseForm!: FormGroup;
expirationCounter!: string;
timeIsUp = false;
donePushed = false;
constructor(
private fb: FormBuilder,
private tasksService: TasksService,
private excuseService: ExcuseService,
private router: Router
) {}
ngOnInit() {
this.tasks = this.tasksService.getTasks();
this.startTimer(86400);
this.excuseForm = this.fb.group({
excuse: '',
});
this.excuseForm.valueChanges.subscribe(console.log);
}
addExcuse() {
const excuseValue = this.excuseForm.value;
this.excuseService.addExcuse(excuseValue);
this.router.navigate(['/loosers']);
}
onTaskDone() {
this.donePushed = true;
}
startTimer(secsToStart: number): void {
// ... (定时器函数的代码)
}
}
HTML部分,计时器在span
中执行,显示在expirationCounter
:
<app-nav-bar></app-nav-bar>
<div *ngFor="let tasks of tasks">
<p>{{ tasks.task }}</p>
<button (click)="onTaskDone()">Done</button>
</div>
<div>
<span id="myTimeCounter">{{ expirationCounter }}</span>
</div>
<div *ngIf="this.timeIsUp">
<form [formGroup]="excuseForm">
<input
type="text"
placeholder="写下你的借口..."
formControlName="excuse"
/>
<button (click)="addExcuse()">Add</button>
</form>
</div>
如果你想在组件加载后仍然保持定时器运行,可以将startTimer
函数的调用移到constructor
中,这样它将在组件初始化时执行而不会在每次重新加载时重新开始计数。
英文:
Im learning angular and facing following question - if i understand right - all what i put in ngOnInit, is executed on each component reload. I have timer function, which needs to keep running also if page is reloaded, not start new count. How can i execute function startTimer(secsToStart: number) outside ngOnInit, or in HTML, or there is other angular feature i need to look into.
The component code:
@Component({
selector: 'app-task-countdown',
templateUrl: './task-countdown.component.html',
styleUrls: ['./task-countdown.component.css'],
})
export class TaskCountdownComponent implements OnInit {
@Input()
tasks!: Tasks[];
excuse!: Loosers[];
excuseForm!: FormGroup;
expirationCounter!: string;
timeIsUp = false;
donePushed = false;
constructor(
private fb: FormBuilder,
private tasksService: TasksService,
private excuseService: ExcuseService,
private router: Router
) {}
ngOnInit() {
this.tasks = this.tasksService.getTasks();
this.startTimer(86400);
this.excuseForm = this.fb.group({
excuse: '',
});
this.excuseForm.valueChanges.subscribe(console.log);
}
addExcuse() {
const excuseValue = this.excuseForm.value;
this.excuseService.addExcuse(excuseValue);
this.router.navigate(['/loosers']);
}
onTaskDone() {
this.donePushed = true;
}
startTimer(secsToStart: number): void {
var start: number = secsToStart;
var h: number;
var m: number;
var s: number;
var temp: number;
var timer: any = setInterval(() => {
h = Math.floor(start / 60 / 60);
temp = start - h * 60 * 60;
m = Math.floor(temp / 60);
temp = temp - m * 60;
s = temp;
var hour = h < 10 ? '0' + h : h;
var minute = m < 10 ? '0' + m : m;
var second = s < 10 ? '0' + s : s;
this.expirationCounter = hour + ':' + minute + ':' + second;
if (start <= 0) {
clearInterval(timer);
this.expirationCounter = 'Expired';
this.timeIsUp = true;
this.tasks = [];
} else if (this.donePushed) {
clearInterval(timer);
console.log(start);
}
start--;
}, 1000);
}
}
The html part, the timer is executed in span as expirationCounter:
<app-nav-bar></app-nav-bar>
<div *ngFor="let tasks of tasks">
<p>{{ tasks.task }}</p>
<button (click)="onTaskDone()">Done</button>
</div>
<div>
<span id="myTimeCounter">{{ expirationCounter }}</span>
</div>
<div *ngIf="this.timeIsUp">
<form [formGroup]="excuseForm">
<input
type="text"
placeholder="write down your excuses .. "
formControlName="excuse"
/>
<button (click)="addExcuse()">Add</button>
</form>
</div>
答案1
得分: 2
当重新加载页面时,Angular 会失去所有已收集的信息(例如当前计数状态)。
您应该考虑在每次计数时将当前计数保存在本地存储中,然后在页面/组件加载时从那里加载它。
// 写入
let mycount: number = 5;
localStorage.setItem("countvalue", String(5));
// 读取
let mycount: string = localStorage.getItem("countvalue");
英文:
When you reload the page angular losses all informations hat has been gathered (like the current count state).
You should consider saving the current count in localstorage on each count and load it from there when the page/components load.
// write
let mycount: number = 5;
localStorage.setItem("countvalue", String("5"));
// read
let mycount: string = localStorage.setItem("countvalue");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论