Save token with isAuthenticated in AUTH_KEY
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
In effects you can inject store and retrieve store data as a part of effect stream with withLatestFrom rxjs operator :)
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 thanks for sharing!