如何在Angular响应式表单中持久化值?

3
我希望在用户跳转到其他组件(如隐私政策)然后回到表单时,可以将值保留在 Angular 表单输入字段中。当用户从隐私政策返回表单时,应该看到之前输入的数据。

你应该使用状态管理将输入数据存储到内存中。 - Tony Ngo
请看这里:https://dev.to/avatsaev/simple-state-management-in-angular-with-only-services-and-rxjs-41p8 - Gopesh Sharma
本地存储...非常适合您的用例。 - Akber Iqbal
3个回答

3
  • 如何在点击保存按钮后持久化数据。

当用户单击保存按钮时,调用以下方法,它会删除旧键并将新表单(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')));
        }
      }

  • 如果用户在没有保存表单的情况下尝试关闭窗口,您有两个选择:要么弹出提示说他有未保存的数据,要么将表单存储在本地存储中。我会在这里结合两种方法。

      @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,您可以处理诸如窗口关闭或页面刷新之类的事件。在其中,我们检查表单是否被修改过,在用户修改表单时才会设置该标志。
您将看到一个问题,即如果用户单击保存并尝试关闭窗口,则仍会弹出窗口,显示用户有未保存的数据。这是因为一旦编辑了表单,它的dirty标志就被设置了。您需要重置它。在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')));

  • 如何在用户未保存数据时导航到其他页面时保存数据的问题。两种选择:
  1. 当用户导航到其他页面时,弹出提示或将数据保存到本地存储中,并创建类似以下内容的保护程序(命令:ng g guard guardname)。

    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' }
    ];

  1. 当用户修改表单时,立即将数据保存到本地存储中--我会留下这部分的研究,因为代码不方便与我共享。

请查看压缩教程:https://tejaxspace.com/storage-local-session/

请查看Angular演示应用程序:https://github.com/tejaswipandava/AngularDataPersistence.git


1

你可以使用 localStorage。它非常易于使用。

var data = "some data";
localStorage.setItem("data_item", data);
localStorage.getItem("data_item"); //returns "some data"

或者

使用 SessionStorage 或 cookies 来存储您的数据。

当您刷新页面时,将您的数据复制到上述任何一种存储中,并在初始化时将其复制回您的变量中。请参考下面的示例。将 sessionStorage 替换为 localStorage 可以将数据存储在 localStorage 中。

In AppComponent

    ngOnInit() {
    if (sessionStorage.getItem("user")) {
      this.data.changeUser(sessionStorage.getItem("user"));
    }
    }
@HostListener('window:beforeunload', ['$event'])
      unloadNotification($event: any) {
        sessionStorage.setItem("user", this.getUser());
    }

0
最佳解决方案 - 使用状态。
最简单的解决方案 - 在输入事件中保存值。 例如:
<input FormControl="name" (input)="saveValue"/>

在你的ts文件中:

saveValue() {
this.name = this.form.get('name').value;
}

当你回到表单时,请调用reBuild函数。

reBuild() {
this.form.get('name').setValue(this.name) ;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接