Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Save token with isAuthenticated in AUTH_KEY #501

Open
Amitshaale opened this issue Dec 17, 2019 · 3 comments
Open

Save token with isAuthenticated in AUTH_KEY #501

Amitshaale opened this issue Dec 17, 2019 · 3 comments

Comments

@Amitshaale
Copy link

Amitshaale commented Dec 17, 2019

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

@tomastrajan
Copy link
Owner

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

@reevesba
Copy link

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)

@tomastrajan
Copy link
Owner

@reevesba thanks for sharing!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants