import { Injectable } from '@angular/core';
import {
ActivatedRouteSnapshot,
CanActivate,
Router,
RouterStateSnapshot,
UrlTree,
} from '@angular/router';
import { Observable } from 'rxjs';
import { UsuarioService } from './usuario/usuario.service';
@Injectable({
providedIn: 'root',
})
export class AutenticacaoGuard implements CanActivate {
constructor(private usuarioService: UsuarioService, private router: Router) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
):
| Observable<boolean | UrlTree>
| Promise<boolean | UrlTree>
| boolean
| UrlTree {
if (!this.usuarioService.estaLogado()) {
this.router.navigate(['home']);
return false;
}
return true;
}
}
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AutenticacaoGuard } from './autenticacao/autenticacao.guard';
const routes: Routes = [
{
path: '',
pathMatch: 'full',
redirectTo: 'home',
},
{
path: 'home',
loadChildren: () => import('./home/home.module').then((m) => m.HomeModule),
},
{
path: 'animais',
loadChildren: () => import('./animais/animais.module').then((m) => m.AnimaisModule),
canLoad: [AutenticacaoGuard],
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule],
})
export class AppRoutingModule {}