简体   繁体   中英

Implement Autosave to Firestore database when using Angular Reactive Forms

I have an Angular app where the data in a form needs to be saved to (and updated from) a Firestore database more or less instantly since 1) multiple people will be entering data on the same form, 2) other users are going to be using the real time values in another part of the application, and 3) the data needs to be saved in case of power or internet failure.

I'm using reactive forms and I've tried saving the form values by subscribing to the form changes and also by triggering individual changes on keyup. For the most part, it works ok, but sometimes the data gets lost.

For example, let's say I type something into a field (eg 123456789). Here is what sometimes happens:

  • As I'm typing, '1234' gets saved to the database
  • I continue typing '567'
  • Once 1234 is updated in the database, it gets emitted to the document's valueChanges observable
  • The form gets patched with '1234'
  • I continue typing '89'
  • The value in the input is now '123489' (discarding the 567 since that got lost when the update happened)

Is there a good way to handle this? I've tried to use debounceTime, but that sort of exacerbates the delay problem.

I've got a sample stackblitz where I simulate the firestore database delay issue ( https://stackblitz.com/edit/immediate-save?file=src/app/app.component.ts ).

ps I'd be OK with holding off on a save until the focus changes (eg blur or (change)), but I would also want to trigger a save if a cursor stops typing in a field, but doesn't tab to the next field

How does adding debounce time exacerbates delay problem? Just add debounce on valueChanges lisener, not database request:

  this.controls.valueChanges
    .pipe(
      debounceTime(500)
    )
    .subscribe(person=>{
      console.log(person);
      this.dataSvc.updatePerson(person);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM