angular-ngrx-material-starter icon indicating copy to clipboard operation
angular-ngrx-material-starter copied to clipboard

Save token with isAuthenticated in AUTH_KEY

Open Amitshaale opened this issue 6 years ago • 3 comments

Hi,

I wanted to save token with AUTH_KEY

this.localStorageService.setItem(AUTH_KEY, { isAuthenticated: true, token: authLogin })

in auth.effect.ts how to pass token

Amitshaale avatar Dec 17 '19 08:12 Amitshaale

In effects you can inject store and retrieve store data as a part of effect stream with withLatestFrom rxjs operator :)

tomastrajan avatar Dec 24 '19 05:12 tomastrajan

Use the props method by updating the following files.

auth.actions.ts export const authLogin = createAction('[Auth] Login', props<{token: string}>());

auth.models.ts export interface AuthState { isAuthenticated: boolean; token: string; }

auth.reducer.ts export const initialState: AuthState = { isAuthenticated: false, token: null };

const reducer = createReducer( initialState, on(authLogin, (state, auth) => ({ ...state, isAuthenticated: true, token: auth.token })), on(authLogout, (state) => ({ ...state, isAuthenticated: false, token: null })) );

auth.effects.ts tap((auth) => this.localStorageService.setItem(AUTH_KEY, { isAuthenticated: true, token: auth.token }))

Note: you don't have to save tokens to local storage. You can retrieve them from the store by setting up a selector. eg:

auth.selector.ts export const selectToken = createSelector( selectAuthState, (state: AuthState) => state.token );

After importing the new selector in core.module.ts, you can retrieve the token like so token$: Observable<string>; token: string; this.token$ = this.store.pipe(select(selectToken)); this.token$.subscribe((val) => this.token = val)

reevesba avatar Jan 17 '21 22:01 reevesba

@reevesba thanks for sharing!

tomastrajan avatar Jan 18 '21 13:01 tomastrajan