Auth Guard
(src/app/auth/auth.guard.ts):
Return true if user is well Authentication
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from './auth.service';
import { Observable } from 'rxjs';
import { take, map } from 'rxjs/operators';@Injectable({
providedIn: 'root',
})
export class AuthGuard implements CanActivate {constructor(private authService: AuthService, private router: Router) {}
canActivate(): Observable<boolean> {
return this.authService.isLoggedIn$.pipe(
take(1),
map(loggedIn => {
if (loggedIn) {
return true;
}
this.router.navigate(['/login']);
return false;
})
);
}
}
App Routing Module
(src/app/app-routing.module.ts):
Protect your route with Guard
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './auth/login/login.component';
import { ProtectedComponent } from './protected/protected.component';
import { AuthGuard } from './auth/auth.guard';const routes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'protected', component: HomeComponent, canActivate: [AuthGuard] },
{ path: '', redirectTo: '/login', pathMatch: 'full' },
];@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}