2017-04-24 113 views
1

我想在打字稿中創建自動保存。目標是獲取任何用戶類型並每隔10秒自動保存一次,這樣即使頁面崩潰或意外關閉,用戶也不會失去輸入的內容。 我想在頁面完成加載後立即開始自動保存過程。異步自動保存在角2打字稿

我寫了這樣的事情:

ngAfterViewInit() { 
    this.autoSaveContent(); 
} 

private autoSaveContent() { 
    while (true) { 
     if (this.isSaving == false && this.hasContentChanged() == true) { 
      this.content.status = 1; 
      setTimeout(this.saveContent(), 10000) 
     } 
    } 

} 

如何異步運行的代碼?因爲我希望此過程在頁面打開時不斷運行。這種方式可以隨時保存內容。

回答

0

以上應該工作!只有我能看到的問題是,您應該在setTimeout方法中傳遞函數引用,而不是在那裏調用它。

setTimeout(this.saveContent.bind(this), 10000) 

OR

setTimeout(() => { this.saveContent() }, 10000) 
1

的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); 
} 
0

感謝您的迴應,但是我發現在Observable中有一個計時器,所以我通過使用計時器來解決它。

ngAfterViewInit() { 
    this.isPageAlive = true; 
    let timer = Observable.timer(10000, 10000); 
    let subscription = timer.subscribe(x => this.autoSaveContent()); 
} 

private autoSaveContent() { 
    if (this.isSaving == false && this.hasContentChanged() == true) { 
     this.content.status = 1; 
     this.saveContent(); 
    } 

}