Search code examples
angularngrxngrx-storengrx-effects

Angular 7 used NGRX and save token in localStorage


In my Angular application i used NGRX store and i have some problem with saved user token. Sometimes i reload my page and lost everything.

In app.component.ts implement OnInit and add there:

this.store.select('auth').subscribe(event => {
  if (event.token) {
    window.localStorage.setItem('token', JSON.stringify(event.token));
  }
});

if (window.localStorage.getItem('token')) {
  const token = JSON.parse(window.localStorage.getItem('token'));
  this.store.dispatch(new AuthActions.SetToken(token));
}

And created Effect:

@Effect()
this.actions$.pipe(
    ofType<AuthActions.TrySignin> (
        AuthActions.AuthActionTypes.TRY_SIGNIN
    ),
        switchMap(action => {
            return this.httpClient.put('http://localhost:8080/api/signin', {
                username: action.payload.username,
                password: action.payload.password
            }, {
                    observe: 'body',
                    responseType: 'text'
                }).pipe(
                    map(
                        token => {
                            this.router.navigate(['/']);
                            return new AuthActions.SetToken(token);
                        }
                    ),
                    catchError(error => {
                        return of(new AuthActions.AuthFailed(error));
                    }
                    )
                );

        }
        )
);

It is correct?


Solution

  • @Injectable()
    export class FormEffects {
      constructor(
        private actions$: Actions<Action>,
        private localStorageService: LocalStorageService
      ) {}
    
      @Effect({ dispatch: false })
      persistForm = this.actions$.pipe(
        ofType<ActionFormUpdate>(FormActionTypes.UPDATE),
        tap(action =>
          this.localStorageService.setItem(FORM_KEY, { form: action.payload.form })
        )
      );
    }