我正在尝试在 typescript 中创建自动保存。目标是获取用户输入的所有内容,并每 10 秒自动保存一次,这样即使页面崩溃或意外关闭页面,用户也不会丢失输入的内容。 我想在页面加载完成后立即开始自动保存过程。
我写过这样的东西:
ngAfterViewInit() {
this.autoSaveContent();
}
private autoSaveContent() {
while (true) {
if (this.isSaving == false && this.hasContentChanged() == true) {
this.content.status = 1;
setTimeout(this.saveContent(), 10000)
}
}
}
如何异步运行代码?因为我希望这个进程在页面打开时不断运行。这样内容就可以一直被保存。
最佳答案
setInterval() 应该每 10 秒检查一次更改...类似这样...
ngAfterViewInit() {
this.autoSaveContent();
}
private autoSaveContent() {
var that = this;
setInterval(function() {
if (that.isSaving == false && that.hasContentChanged() == true) {
that.saveContent();
}
}, 10000);
}
对于 ES6,您可以使用粗箭头,而不必担心在闭包中捕获“this”:
private autoSaveContent() {
setInterval(() => {
if (this.isSaving == false && this.hasContentChanged() == true) {
this.saveContent();
}
}, 10000);
}
关于angular - 在 Angular 2 typescript 中异步自动保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43596477/