Last active
June 11, 2018 09:04
-
-
Save alanxone/9dcef175f86c23a477b6f88a30b8b21b to your computer and use it in GitHub Desktop.
NGRX Tutorial - Auth Effect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// NGRX Complete Tutorial Without Pain (Angular6 / RxJS6) | |
// https://medium.com/@andrew.kao/ngrx-complete-tutorial-without-pain-angular6-rxjs6-5511b8cb8dac | |
import { Injectable } from '@angular/core'; | |
import { Effect, Actions, ofType } from '@ngrx/effects'; | |
import { tap, map, exhaustMap, catchError } from 'rxjs/operators'; | |
import { Router } from '@angular/router'; | |
import { of } from 'rxjs'; | |
import { AuthService } from '(service path to request backend data)'; | |
import { Permission } from '(service path to request backend data)'; | |
import { Authentication } from '(authentication model)'; | |
import { | |
Login, | |
LoginSuccess, | |
LoginFailed, | |
AuthActionTypes, | |
} from ('auth action path)'; | |
@Injectable() | |
export class AuthEffects { | |
@Effect() | |
// Once it detects such signal (it's a string as we defined in "Action") | |
// It will call | |
login$ = this.actions$.pipe( | |
ofType(AuthActionTypes.Login), | |
map((action: Login) => action.payload), | |
// Use `exhaustMap` to wait for Observable respond | |
exhaustMap((auth: Authentication) => | |
this.authService | |
.login(auth) | |
.pipe( | |
map(username => new LoginSuccess(username)), | |
catchError(error => of(new LoginFailed(error))) | |
) | |
) | |
); | |
@Effect({ dispatch: false }) | |
// If the user is logged in, let it goes to "Team App" | |
loginSuccess$ = this.actions$.pipe( | |
ofType(AuthActionTypes.LoginSuccess), | |
tap(() => this.router.navigate(['/team'])) | |
); | |
@Effect({ dispatch: false }) | |
// Probably the user enter some routes directly, and we require it to login | |
// As for permission, we can do the same thing to redirect it to somewhere for requesting the permissions | |
loginRedirect$ = this.actions$.pipe( | |
ofType(AuthActionTypes.LoginRequired), | |
tap(() => { | |
this.router.navigate(['/auth']); | |
}) | |
); | |
constructor( | |
private router: Router | |
private actions$: Actions, | |
private authService: AuthService, | |
) {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment