canActive used for protect routes in angular 4
Create auth.service.ts file
–auth.service.ts
export class AuthService {
loggedIn = false;
isAuthenticated(){
const promise = new Promise(
(resolve, reject) => {
setTimeout(() => {
resolve(this.loggedIn)
}, 800);
}
)
return promise;
}
login() {
this.loggedIn = true;
}
logout(){
this.loggedIn = false;
}
}
Create auth-guard.service.ts file
–auth-guard.service.ts
import { Injectable } from "@angular/core";
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from "@angular/router";
import { Observable } from "rxjs/Observable";
import { AuthService } from "./auth.service";
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot ): Observable | Promise | boolean {
return this.authService.isAuthenticated()
.then(
(authenticated: boolean) => {
if(authenticated) {
return true;
} else {
this.router.navigate(['/']);
}
}
)
}
}
Add into routing code.
const appRoutes: Routes = [
{ path: '', redirectTo:'/home', pathMatch:'full'},
{ path: 'home', component: HomeComponent},
{ path: 'users', component: UsersComponent, children: [
{ path: ':id/:name', component: UserComponent},
]},
{ path: 'servers', canActivate:[AuthGuard], component: ServersComponent, children: [
{ path: ':id', component: ServerComponent},
{ path: ':id/edit', component: EditServerComponent},
]},
{ path: 'error-404', component: Page404Component},
{ path: '**', redirectTo: '/error-404'}
]
Now you can see, you not able to go servers page.