Skip to content

Instantly share code, notes, and snippets.

@alanxone
Last active May 11, 2021 23:45
Show Gist options
  • Save alanxone/d5b87c907e100d68d2d1b484e8f62459 to your computer and use it in GitHub Desktop.
Save alanxone/d5b87c907e100d68d2d1b484e8f62459 to your computer and use it in GitHub Desktop.
NGRX Tutorial - Auth Guard
// 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 { CanActivate } from '@angular/router';
import { Store, select } from '@ngrx/store';
import { Observable } from 'rxjs';
import { map, take } from 'rxjs/operators';
import * as Auth from '(auth actions)';
import * as fromTeam from '(team main reducer)';
// Basically, "Permission" needs guard but I'm not going to do here
// The logic is very similiar
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private store: Store<fromTeam.TeamState>) {}
canActivate(): Observable<boolean> {
return this.store.pipe(
select(fromTeam.getAuthStatus),
map(authed => {
// `authed` is boolean as we defined in "Actions" as `isAuthenticated`
if (!authed) {
// Dispatch an event to let "Effects" navigate users to login
this.store.dispatch(new Auth.LoginRequired());
return false;
}
// Let "Router" allow user entering the page
return true;
})
);
}
}
@bonino97
Copy link

Doesnt work, if you are logged and the url is reloaded, the guard return false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment