I lose information about user when refreshing page? Angular 2+ NgRx store

how to detect page refresh in angular 6
how to keep form data when switching tabs/routes?
angular 2 persist data on refresh
angular 7 keep data after refresh
how to keep behaviorsubject data on page reload
confirmation before closing of tab/browser using angular 2
angular beforeunload
angular 2 hostlistener onbeforeunload

I need to post user info but I am losing it to refresh. How to set up isAuthenticated variable that we do not lose value on refresh? Maybe you don't need to look at most of this code just to tell me how to fix it now Piece of my code which you need:


  getState: Observable<any>;
  isAuthenticated: false;
  user = null;
  errorMessage = null;
  globalisAuthenticated = null;
  constructor(public dialog: MatDialog, private store: Store<AppState>) {
    this.getState = this.store.select(selectAuthState);
  ngOnInit() {
    this.getState.subscribe((state) => {
      this.isAuthenticated = state.isAuthenticated;
      this.user = state.user;
      this.errorMessage = state.errorMessage;
      // console.log("is" , this.isAuthenticated)
      localStorage.setItem("isAuthenticated", state.isAuthenticated);


export interface State {
  // is a user authenticated?
  isAuthenticated: boolean;
  // if authenticated, there should be a user object
  user: User | null;
  // error message
  errorMessage: string | null;

export const initialState: State = {
  isAuthenticated: false,
  user: null,
  errorMessage: null

    export function reducer(state = initialState, action: All): State {
      switch (action.type) {
        case AuthActionTypes.LOGIN_SUCCESS: {
          return {
            isAuthenticated: true,
            user: {
              token: action.payload.token,
              email: action.payload.email
            errorMessage: null
        case AuthActionTypes.LOGIN_FAILURE: {
          return {
            errorMessage: 'Incorrect email and/or password.'
        default: {
          return state;


LogIn: Observable<any> = this.actions
  .map((action: LogIn) => action.payload)
  .switchMap(payload => {
    return this.authService.logIn(payload.email, payload.password)
      .map((user) => {
        return new LogInSuccess({token: user.token, email: payload.email});
      .catch((error) => {
        return Observable.of(new LogInFailure({ error: error }));

  @Effect({ dispatch: false })
LogInSuccess: Observable<any> = this.actions.pipe(
  tap((user) => {
    console.log("User",  user);
    localStorage.setItem('token', user.payload.token);
    this.snackBar.open("Uspesno ste ste prijavili.", null, {
      duration: 5000,
      verticalPosition: 'bottom',
      horizontalPosition: 'right'


export interface AppState {
  authState: auth.State;

export const reducers = {
  auth: auth.reducer

export const selectAuthState = createFeatureSelector<AppState>('auth');

Can you tell me a way to avoid losing data on refresh? if you need more information just ask me. This is doing all right for now. But when I do refresh I lose everything but the token is here in localstorage.

UPDATE UPDATE UPDATE I am added this but again no work

  import { StoreModule, ActionReducerMap, ActionReducer, MetaReducer } from '@ngrx/store';
  import { localStorageSync } from 'ngrx-store-localstorage';
  import { reducers } from './reducers';

  // const reducers: ActionReducerMap<IState> = {todos, visibilityFilter};

  export function localStorageSyncReducer(reducer: ActionReducer<any>): ActionReducer<any> {
    return localStorageSync({keys: ['todos']})(reducer);
  const metaReducers: Array<MetaReducer<any, any>> = [localStorageSyncReducer];

It is normal that you lose state on refresh. You will need to persist the state yourself or use a library such as https://www.npmjs.com/package/ngrx-store-localstorage .

Angular: Keeping the User from Losing Data by Leaving the Page , In order to keep the user from losing data, due to navigation changed within the Angular app or in the browser level (like close/refresh), we need to create a generic component to handle any form component. It will return that data is unsaved when the form is actually left, not submitted and dirty. User clicks the 'back' button in the browser, dialog displays, and user clicks CANCEL. User clicks the 'back' button again, dialog displays, and user clicks CONFIRM. Note: user is navigated back 2 times, which could even take them out of the app altogether :(This has been discussed here, here, and at length here

you can save this value to localStorage of the browser as :

localStorage.setItem("auth", JSON.stringify(this.isAuthentificated));

then, when you access the app, get the value.

this.isAuthentificated = JSON.parse(localStorage.getItem("auth"));

But, when you log out, you need to set the value false on localStorage, or to delete the key. (I prefer the first one)

1) localStorage.removeItem("auth"); or

2) localStorage.setItem("auth", false);

Save service data to avoid loss when user refresh a page : Angular2, ts sending user action and receiving results) -> score (show results using current info downloaded from logic.service.ts . Places which need to store data when� I detected problem in my application - loss data when refresh a page, so I looked for solution and found: localstorage, window:beforeunload and canDeactivate, but I need to understand how to implement this in my case. My application is a board game. It has logic.service.ts which contains players info and state of the game.

Try this

  export function localStorageSyncReducer(reducer: ActionReducer<any>): ActionReducer<any> {
     return localStorageSync( {keys: ['auth'], rehydrate: true})(reducer);

Store information on page reload in Angular 4 : Angular2, Hi all, in my app i'm storing information into service to avoid the local storage and The problem is when the user reload the page (ctrl + f5 or cmd +R for clarity) Also if someone does a hard reload all clientside data is lost (except cookies I� Maintaining session info in AngularJS when you refresh the page Maff Posted on July 2, 2013 Posted in AngularJS , Code , MVC , Razor , Web development — 36 Comments ↓ EDIT: This article has proved to be the most popular article on my site, but I thought it was a bit “rambly” and also the code examples were out of date.

This is what you should expect from NgRx. You will need to re-fetch the user each time the browser is refreshed. There are multiple ways of doing this. I use JWT authentication, so the state update process looks something like this:

  1. User logs in by typing username and password
  2. Angular authenticates the user successfully and saves the issued JWT to localStorage.
  3. User refreshes page, which causes state to be lost. That is not a problem, because in the Component's ngOnInit() hook, your code should check for the JWT token. If it doesn't find a JWT in local storage, it immediately sets the authentication state to "logged out". If it does find a JWT token, it dispatches a new action, which we will call GET_USER.
  4. The GET_USER action will have a single effect. This effect will send out an API GET request to your /api/user route.

At this point, you're probably wondering two things. First, you might wonder what the purpose of a GET request is? Well, the GET request will not work immediately. Obviously, you will need some sort of HTTP Header to send along with the GET request so that the backend can figure out which user you are trying to get. To do this, you can set up an HttpInterceptor. This interceptor will intercept every outgoing HTTP request and attach the JWT token that is stored in localStorage.

Secondly, you might wonder how the backend is going to use a JWT token to find a user in a database. The backend /api/user route will do the following:

  1. Grab the JWT token from the HTTP Authorization header (which was populated by the Angular HttpInterceptor)
  2. Verifies the JWT with a library such as jsonwebtoken
  3. If JWT is valid, the jsonwebtoken library will decode it. When you issued the token, you should have saved the user ID on the sub property of the JWT payload. You can now use that sub property to retrieve the user from the database.
  4. Return the retrieved user

Alright, so we can return to the original flow. Remember, all of this was caused by the GET_USER action which had an effect that made a GET request to /api/user

  1. At this point, you should have access to the user object in the effect. You now will return another action such as GET_USER_SUCCESS, and pass the user object as an argument to this action.
  2. GET_USER_SUCCESS will have a reducer that will set the authentication state of the application. For example, you might set a property isAuthenticated to true and a property user to the user object attached to the GET_USER_SUCCESS action payload.

In summary, the fact that NgRx is clearing state on each refresh is by design. Populating the user on page load is certainly not a simple process, but once implemented, you will have a predictable user authentication flow.

My Angular app is losing it's auth state when I refresh the page , But when I refresh my Angular 7 app, the auth state is lost. How can I keep the auth state when refreshing the page? localHostAlert. js-error. James. log” to catch redirects and scrub the file of user passwords before passing it over to How to troubleshoot with HAR files and steps to generate a HAR file. If you are working with Angular and need to refresh a component without navigation on another component without using window.location.reload() or location.reload(), you can use the following code

Angular 7, I have followed the angular 2 quickstart guide, but no matter what, on page refresh/new tab opened for the angular app, the user is forced to� Angular 2 was released in October this year. On the Internet you can find more and more tutorials which shows how to build a simple application. This tutorial is quite different from them. It shows how to build an Angular 2 application where we’re going to focus on architecture which will periodically pull data from backend to keep fresh data

Angular Basics: Refresh an Angular Component without reloading , In this article, we provide a brief tutorial on how to refresh an Angular component without This snippet will work in Angular 2, 4, 5, 6, 7, and 8. Hi all, in my app i'm storing information into service to avoid the local storage and the possibility to leak information about the variable i need to know into a particular page. The problem is when the user reload the page (ctrl + f5 or cmd +R for clarity) because the service reset the informations stored in it.

Data and Page Content Refresh patterns in Angular - DEV, Tagged with angular, angular2, rxjs, observable. A user action in the application causes the data to change (especially, if it does so in ways� Guards in Angular 2 are used to protect routes, there are a few different guard types depending on the specific behaviour you want to implement, in this example I'm using a CanActivate guard which implements a single canActivate() method that enables you to check if a route can be activated or not, which in this case is if the user is

  • You have to add the metaReducers to your StoreModule, like this: StoreModule.forRoot(reducers, { metaReducers, ... }
  • Do you have any tutorial on how to implement this package? I am new in angular
  • @AleksandarMihailovic: I don't, but the instructions in the package are straightforward and include sample code.
  • Did you using package ? I copy/paste example of code but again no work. Look update answear.
  • Did you add it to the current module and register the metaReducers like in the example? It is not clear from your description where you added the code.
  • Look my image ibb.co/7K93yLh But I also have one reduce before this from my state import { reducers } from './store/app.states'; This is module.app file @cisse
  • Did I can store my boolean variable isAuthentificated ?
  • yes, you can store it, but you need to update or create/delete it at login/logout
  • can you tell me what is exactly keys? What is auth? From location this data coming ? Thanks