I am new to angular and spend around 2 to 3 hours online trying to navigate from login to dashboard if user authenticates. I am able to route to dashboard if I don't user canActivate: [AuthGuard]. However as soon as I add canActivate: [AuthGuard] I am stuck on the login page(though I see the user SignIn on firebase console). Its just not navigating me to dashboard page
My code..
app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from './components/dashboard/dashboard.component';
import { AuthGuard } from './shared/guard/auth.guard';
//import { SecureInnerPagesGuard } from "./shared/guard/secure-inner-pages.guard.ts.guard";
//import { HomeComponent } from './components/home/home.component';
import { SignInComponent } from './components/sign-in/sign-in.component';
import { from } from 'rxjs';
const routes: Routes = [
{ path: '', redirectTo: '/sign-in', pathMatch: 'full'},
{ path: 'sign-in',component: SignInComponent},
{ path: 'dashboard', component: DashboardComponent, canActivate: [AuthGuard] },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
auth.guard.ts
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from '../../auth/auth.service';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(
public authService: AuthService,
public router: Router
){ }
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if(this.authService.isLoggedIn !== true) {
this.router.navigate(['sign-in']);
}
return true;
}
}
I've also added [AuthGuard] in Providers of app.module.ts Any help would be appreciated
looks like your if(this.authService.isLoggedIn !== true) condition returns true and your app navigate to the route sign-in
. check if the this.authService.isLoggedIn
becomes true when your login success.
Also you don't need if(this.authService.isLoggedIn !== true)
you can just use if(!this.authService.isLoggedIn)
.