I'am using CanActivate
feature for my router and its child, but it doesn't work - Have been using the same couple of months ago, but now not.
There is no error, warning or something similar I can debug... the app just run and I can reach the router I want to protect normal as all the other routes.
Could you please see what's wrong with the following code? The problem is that I even doesn't get any error.
As Info I'am using Angular 5.
app.router.ts
:
export const router: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full'},
{ path: 'home', component: HomeComponent},
{ path: 'signup', component: SignupComponent},
{ path: 'dashboard', canActivate: [ AuthguardGuard ],
children:
[
{ path: '', loadChildren: './dashboard/dashboard.module#DashboardModule', pathMatch: 'full' }
]
},
{ path: '**', redirectTo: 'page-not-found' }
];
export const appRoutes: ModuleWithProviders = RouterModule.forRoot(router);
dashboard.module.ts
:
const dashboardRoutes: Routes = [
{ path: 'user', redirectTo: 'user', pathMatch: 'full' },
{ path: 'user', component: UserComponent,
children: [
{ path: '', component: EditComponent },
{ path: 'userMail', component: UserMailComponent },
{ path: 'userSettings', component: UserSettingsComponent}
]
},
];
authguard.guard.ts
:
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './_service/auth.service';
@Injectable()
export class AuthguardGuard implements CanActivate {
constructor( private user: AuthService ) {
console.log('In AuthGuard!');
}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
return this.user.isUserAuthenticated();
}
}
auth.service.ts
:
import { Injectable } from '@angular/core';
@Injectable()
export class AuthService {
public isUserAuthenticated;
private userName;
constructor() {
this.isUserAuthenticated = false;
}
setUserLoggedIn() {
this.isUserAuthenticated = true;
}
getUserLoggedIn() {
return this.isUserAuthenticated;
}
}