UNPKG

ngrx-amine-auth-jwt

Version:

Ngrx authentification System By Med Amine

71 lines (61 loc) 2.71 kB
import {Injectable} from '@angular/core'; import {Actions, ofType, Effect} from '@ngrx/effects'; import {Router} from '@angular/router'; import {Observable, pipe, of} from 'rxjs'; import {map, switchMap, tap} from 'rxjs/operators'; import {CustomAuthActionTypes, CustomLogInAction, CustomLogInSuccessAction, CustomLogInErrorAction} from '../actions/custom-login-page.action'; import {NgrxAmineAuthService} from '../../ngrx-amine-auth.service'; @Injectable() export class CustomAuthEffects { constructor( private actions: Actions, private customAuthService: NgrxAmineAuthService, private router: Router, ) { } @Effect({dispatch: true}) CustomLogin: Observable<any> = this.actions .pipe( ofType(CustomAuthActionTypes.LOGIN), map((action: CustomLogInAction) => action.payload), switchMap((payload: any) => { console.log('Library payload effect'); console.log(payload); return this.customAuthService.login(payload.email, payload.password) .then(user => { console.log('Library login Success , Effect Response'); console.log(user); // return of(user); return new CustomLogInSuccessAction(user); }).catch(err => { console.log('Library login error , Effect Response'); console.log(err); return new CustomLogInErrorAction({ email: payload.email, errorMessage: err.toString() }); }); })); @Effect({dispatch: false}) CustomLogInSuccess: Observable<any> = this.actions .pipe( ofType(CustomAuthActionTypes.LOGIN_SUCCESS), tap((user: any) => { console.log(CustomAuthActionTypes.LOGIN_SUCCESS + ' Effect Library'); console.log(user); localStorage.setItem('_token', user.payload._token); this.router.navigateByUrl('/home'); }) ); @Effect({dispatch: false}) CustomLogout: Observable<any> = this.actions .pipe( ofType(CustomAuthActionTypes.LOGOUT), tap((user: any) => { console.log(CustomAuthActionTypes.LOGOUT + ' Effect Library'); console.log(user); localStorage.removeItem('lib-state'); this.router.navigateByUrl('/auth/login'); }) ); }