Angular 8 Loose Data After Refresh Page

Angular 8 loose data after refresh page

When you refresh the page it does not persist variable values, you need to store either in local storage or cookie.

A simple way to solve this is to use this lib:

https://www.npmjs.com/package/ng2-cookies

To install this library, run:

npm install ng2-cookies

Component

import { Cookie } from 'ng2-cookies/ng2-cookies';

ngOnInit() {
this.model.isAdmin = Cookie.get('isAdmin');
}

login() {
this.authService.login(this.model).subscribe(next => {
Cookie.set('isAdmin', 'true');
this.alertify.success('Logged in as Admin')
}, error => {
this.alertify.error(error)
}, () => {
this.router.navigate(['/projects'])
})
}

you can use ngx-cookie-service also

https://www.npmjs.com/package/ngx-cookie-service

Angular, data loss when page refresh

Data stored in variables in services will be cleared if the browser is refreshed . One way to solve this is by using session or local storage to store the data:

    handleDetails(value) {
localStorage.setItem('key', value);
}

To retrieve data from local storage:

localStorage.getItem('key');

loss data when refresh page angular 8

I assume you don't want the user to login again after a page refresh. You already stored the token in the localStorage but after the refresh you have to read it from the same place. You could add a method, for example, in your AccountServicesService:

  getTokenFromLocalStorageWithoutLogin() {
const token = localStorage.getItem('token');
this.test$.next(this.roleTypeForCheck(token));
}

Angular View Component Data Loss during Reload Refresh using BehaviorSubject

I will propose you to use localStorage within your SummaryComponent within ngOnDestroy lifecycle hook. It will always set your data within localStorage before component will be destroyed due to refresh. Then when you are trying to retrieve data from the service, if it will be empty try to get it from localStorage.

export class SummaryComponent implements OnInit, OnDestroy {

salutation: string;
firstName: string;

constructor(
private router: Router,
public userService: UserService
) {
}

ngOnInit(): void {
this.userService.salutation.subscribe(c => { this.salutation = c || localStorage.get('salutation'); });
this.userService.firstName.subscribe(c => { this.firstName = c || localStorage.get('firstName'); });
}

ngOnDestroy(): void {
localStorage.setItem('salutation', this.salutation));
localStorage.setItem('firstName', this.firstName));
}

}

Similar implementation you can do in the component where this values are set and you expect that user can refresh the page before go to the next page.

EDIT

Sorry, you are right that ngOnDestory will not trigger on page refresh to do that you will need to handle window:beforeunload.

  @HostListener('window:beforeunload', ['$event'])
beforeunload($event: Event): void {
// set localStorage here
}

Going forward with your solution, the best option to set items to the localStorage is the place where you set values to the service. It's probably goToDetails2 method.

goToDetails2(form : NgForm) {
this.userService.salutation = new BehaviorSubject(form.value.salutation);
this.userService.firstName = new BehaviorSubject(form.value.firstName);
localStorage.setItem('salutation', form.value.salutation));
localStorage.setItem('firstName', form.value.firstName));
}

EDIT-2 to your problem described in the comment

I will propose you to initialize your BehaviorSubject directly inside of the service.

@Injectable({
providedIn: 'root'
})

export class UserService {

//Details Page 1
public salutation: BehaviorSubject<string> = new BehaviorSubject('');
public firstName: BehaviorSubject<string> = new BehaviorSubject('');

And then within your Details1Component set values on them using next

goToDetails2(form : NgForm) {
this.userService.salutation.next(form.value.salutation);
this.userService.firstName.next(form.value.firstName);
localStorage.setItem('salutation', form.value.salutation));
localStorage.setItem('firstName', form.value.firstName));
}

Data saved in service lost on page refresh or change

A few things look out of order here.

  1. Dependency Injection wrong

You're injecting your WM API service into the component, and then configuring it there. This should not be the case, you should do this on the service itself, and on init. And the service should not be in a "ready" state until it gets this google API data. For one, your component should not be concerned with configuring services - it's only asking for the services and using them. Second, if you use service in other places, e.g. when there is no login component, who is then going to configure your service? And third, if you have multiple instances of the service, that likely means that you are doing it wrong - you should provide the services on global app level so that they all use the same instance, but even if not, you still need to have the service take care for its dependencies, not the service consumers.

Steps to remedy this specific part:

  • take out the gapi.load() etc stuff out of the component and put it in the service
  • provide the service on app level, not on the component (or lazy module) level, if at all possible.


    1. Page reload issue

Possibly some of this stuff is persistent - you say that on page reload, you lose stuff. That is only logical - on each page reload, the stuff from memory dissapears and you have a fresh new app. Perhaps you want to store things like JWT tokens and access stuff into sessionStorage or localStorage. If there is such stuff that needs to persist accross page reloads, you should also build and provide a storage service in your app that offers serialization/deserialization services to your WM API Service (and others). Again, WM Api service is injected with this storage so it can configure itself on startup (in it's constructor).


  1. Http wrong

Http, Headers, Response and basically the entire @angular/http is deprecated in Angular 4.3 - you should use HttpClient and friends from @angular/common/http. The change should be really simple and it's worth it.
Also, try and ween yourself out of .toPromise() on the Http client and into the observables. It'll make working with other things (also observables) easier accross the app, and the change is also relatively minimal - Http(Client) observables complete anyway after success or failure, so your logic should still be the same (just use subscribe(successHandler, errHandler) instead of then(successHandler, errHandler)).


  1. Document

I see you are also using document.getElementById (and possibly other stuff). You would be much better off not to use the browser globals directly, and inject Angular-provided proxies instead. In the long run, you'll thank yourself you did this.

How to keep shared data after page refresh in Angular?

You can keep your data either in session storage or local storage as soon as you get the data.

You can store maximum of 10MB of data in local storage and 50 data points is a very small, i don't think it will be an issue.

You can definitely do that from component itself but It is recommended to write code in service if it has nothing to do with component. Right now you are storing data in local storage so use service. It will keep your code less messy and scalable.

Let say you want to perform some manipulations before storing them to local storage in future, you can easily do that in service class. Isolation always helps as your application grow.

I hope it helps.

Keep data in page after refresh

This can be done with a localStorage.

An example:

localStorage.removeItem('Array');
localStorage.setItem('Array', JSON.stringify(this.array));

The above is how you save it to get it back you do this in the ngOnInit:

this.array = JSON.parse(localStorage.getItem('Array'));
localStorage.removeItem('Array'); // to clear it again.

EDIT

Import:

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

Implement it on your component(class):

export class YourClass implements OnInit

And after constructor:

ngOnInit() { // your code here }


Related Topics



Leave a reply



Submit