angular - 在 Angular 2 typescript 中异步自动保存

标签 angular typescript asynchronous

我正在尝试在 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/

相关文章:

reactjs - new window.Image() 不适用于 typescript/react

perl - 如何将 MojoX::Redis 结果分配给变量?

javascript - 如何在 Node js 中使用异步和等待从数据库中选择

javascript - 如何将一个网址重定向到另一个网址?

javascript - Angular 2 - 绑定(bind)不能包含分配

typescript - 不知道如何使用 angular2 类中的接口(interface)实现枚举

javascript - 如何使用 Vue 类组件访问 VueJS 3 和 Typescript 中的 HTML 引用?

asynchronous - Future.error 和 dart Future 中的 throw 有什么区别?

typescript - Angular 2 导入语句通配符语法

angular - 使用angular-cli在angular2前端构建错误