-2

I am new to Angular and have a query regarding data persistent. I have a scenario where I have to persist data. I am on my homepage component where I have a personal details form which is reactive on /personaldetails path. User needs to fill data and click on the next button to move to the next page on the path /education where there is another form.

It may happen user feels he has to correct some data on personal details page. He clicks on back button and moves from /education to /personaldetails.

Here I want to persist data. I want that data in the input field to be as it is which was enter by user when he was on /personaldetails.

How can I achieve this?

Please share any working code or any reference which will help me. I tried searching similar queries but no luck.

Neo Anderson
  • 5,957
  • 2
  • 12
  • 29
Jay
  • 375
  • 2
  • 5
  • 17
  • You can save the data server side between each step, or use `localStorage` on the client – David Mar 25 '18 at 17:55
  • see this https://stackoverflow.com/questions/49387889/passing-data-with-subjects-and-proxies/49388249#49388249 – Vikas Mar 25 '18 at 17:59
  • @David: I wouldn't recommend this, because localStorage survives the session. So there is a slight change that "old" data gets prompted when the user opens the app days later. –  Mar 25 '18 at 18:00

1 Answers1

0

Use a service to persist the entries:

import { Injectable } from '@angular/core';

    @Injectable()
    export class StorageService {

        private value: string;

        constructor() { }

        getValue(): string {
           return this.value;
        }

        setValue(value: string) {
            this.value = value;
        }
   }

When the user clicks "next" you simply store his entries inside this service. When the user clicks "back" you can get the already entered values from the service.

Attention! You have to import and provide this service by the corresponding module.

And in your component you do it this way:

import {StorageService} from 'storage.service.ts';

constructor(
 private storageService: StorageService
){}

private saveEntries(): void {
  this.storageService.setValue(entries);
}

Of course "entries" doesn't have to be a string. It can be any kind of primitive or object.

  • It depends what OP wants. If he wants data to persist if the use refreshes the page, this won't work – David Mar 25 '18 at 18:04
  • Point taken. But even then I'd suggest to use the sessionStorage instead of the localStorage, because if one closes the browser, the sessionStorage get's killed, the localStorage not. –  Mar 25 '18 at 18:06