I do not know if I let some detail pass, or if I did something wrong, but I can not find what is causing the error. My goal is to do something that will keep checking if the user is logged in each time he accesses a route within pages.. I use Angular 5.
App.module:
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { LoginComponent } from './pages/autenticacao/login.component';
import { AuthService } from './auth/auth.service';
import { RoutesInterceptor } from './auth/routes.interceptor';
import * as $ from 'jquery';
@NgModule({
declarations: [ AppComponent, LoginComponent ],
imports: [
BrowserModule,
BrowserAnimationsModule,
AppRoutingModule,
],
bootstrap: [AppComponent],
providers: [ AuthService, RoutesInterceptor, ],
})
export class AppModule {
}
Routes.intercpetor:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class RoutesInterceptor implements CanActivate {
constructor(private auth: AuthService) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
return this.auth.isUserAuthenticated();
}
}
My Routes:
import { NgModule } from '@angular/core';
import { ExtraOptions, RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './pages/autenticacao/login.component';
import { RoutesInterceptor } from './auth/routes.interceptor';
const routes: Routes = [
{ path: 'pages', loadChildren: 'app/pages/pages.module#PagesModule', canActivate: [RoutesInterceptor] },
{ path: 'login', component: LoginComponent },
{ path: '', redirectTo: 'pages', pathMatch: 'full' },
{ path: '**', redirectTo: 'pages' },
];
const config: ExtraOptions = {
useHash: true,
};
@NgModule({
imports: [RouterModule.forRoot(routes, config)],
exports: [RouterModule],
})
export class AppRoutingModule {
}
Another issue that can cause this is if you try to use a CanActivate
guard as another type of guard, like CanActivateChild
I changed that part of the code and it worked
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class RoutesInterceptor implements CanActivate {
constructor(private auth: AuthService, private route: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (this.auth.isUserAuthenticated()) {
return true;
}
this.route.navigate(['./login']);
return false;
}
}
I forgot to redirect if you have not logged in
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With