I am actually learning Angular and firebase, I want to add a route guard to users dashboard so that only logged in users can view the page. The Authentication works fine but I am having issues restricting none logged in users to access users dashboard This is my code below.
Authservice.service.ts
@Injectable({
providedIn: 'root'
})
export class AuthServiceService {
newUser: any;
// passing Error message
private eventAuthError = new BehaviorSubject<string>('');
eventError$ = this.eventAuthError.asObservable();
showSuccessCreated: boolean;
constructor( private authz: AngularFireAuth, private db: AngularFirestore, private route:Router)
{ }
// geting user details
getUserState() {
return this.authz.authState;
}
// LoggIn Users
login(email: string , password: string ) {
this.authz.auth.signInWithEmailAndPassword(email, password)
.catch( error => {
this.eventAuthError.next(error);
}).then(userCredential => {
if (userCredential) {
this.route.navigate(['/dashboard']);
}
});
}
This is the Authguard service, I try to reference the login method from my authservice.service.ts, but it still redirects to users' dashboard despite I am not Logged In.
authguard.service.ts
export class AuthguardService implements CanActivate {
constructor(private authservice: AuthServiceService, private route: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let isAuthenicated = !!this.authservice.login;
if(isAuthenicated ){
return true;
}
console.log('Access denied');
this.route.navigate(['/login']);
return false;
}
}
route.module.ts
const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent, canActivate:[AuthguardService],
children: [
{path: '', redirectTo: 'employees', pathMatch: 'full'},
{path: 'employees', component: EmployeelistComponent, resolve: {employeeList: ResolverGuardService}},
{path: 'detail/:id', component: EmployeeDetailComponent, canActivate: [CanActivateGuardService],
{ path: 'notfound', component: PageNotFoundComponent},
]
},
];