当用户单击“保存”按钮时,我们调用下面的方法,它会删除旧密钥并将新表单(MessageForm)数据保存在本地存储中。
onSave() {
//removes the data with key as user
localStorage.removeItem("teja");
//adds new data with key as user
localStorage.setItem("teja", JSON.stringify(this.MessageForm.value));
//reset form once form is edited dirty flag is set
//so we need to reset form else on close we get
//notification saying form is dirty even when user clicked on save
this.MessageForm.reset(JSON.parse(localStorage.getItem('teja')));
}
当我们再次加载页面时,我们可以使用键“teja”从该存储中检索数据
ngOnInit(): void {
//retrieves data if exists.
if (localStorage.getItem('teja')) {
this.MessageForm.setValue(JSON.parse(localStorage.getItem('teja')));
}
}
- 用户修改了表单而不保存并尝试关闭窗口,您有 2 个选择,要么弹出窗口说他有未保存的数据,要么将表单存储在本地存储中。我将在这里混合它们。
@HostListener('window:beforeunload', ['$event']) unloadNotification($event: any) {
if (this.MessageForm.dirty) {
//store data
localStorage.setItem("teja", JSON.stringify(this.MessageForm.value));
//show popup
$event.returnValue = true;
}
}
使用hostistener,您可以处理窗口关闭或页面刷新等事件。在其中,我们检查表单是否脏,仅当用户修改表单时才设置。
您将看到的一个问题是,如果用户单击“保存”并尝试关闭窗口,您仍然会收到弹出窗口,提示用户有未保存的数据。这是因为一旦编辑了表单,就会设置其脏标志。您需要重置它。
最后将以下逻辑添加到 Onsave 中
//reset form once form is edited dirty flag is set
//so we need to reset form else on close we get
//notification saying form is dirty even when user clicked on save
this.MessageForm.reset(JSON.parse(localStorage.getItem('teja')));
- 谈到当用户导航到不同页面而不保存数据时如何保存数据的问题。两种选择
- 当用户导航到不同页面时弹出窗口或保存数据
到 localstorage 创建一个如下所示的守卫(命令: ng g Guard
保护名)
import { AppComponent } from './../app/app.component';
import { Injectable } from '@angular/core';
import { CanActivate, CanDeactivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UnsavedataGuard implements CanDeactivate<unknown> {
canDeactivate(
component: AppComponent): boolean {
if (component.MessageForm.dirty) {
localStorage.setItem("teja", JSON.stringify(component.MessageForm.value));
return confirm('Are you sure you want to continue? Any unsaved changes will be lost');
}
return true;
}
}
更新您访问守卫的路线
const routes: Routes = [
{ path: '', component: AppComponent, canDeactivate: [UnsavedataGuard] },
{ path: '**', component: AppComponent, pathMatch: 'full' }
];
- 用户修改表单时将数据保存到本地存储 - 我将离开这部分的研究,因为代码对我来说不方便????
请查找缩小版教程:https://tejaxspace.com/storage-local-session/ https://tejaxspace.com/storage-local-session/
请找到一个 Angular 演示应用程序:https://github.com/tejaswipandava/AngularDataPersistence.git https://github.com/tejaswipandava/AngularDataPersistence.git