auth.guard.ts
import {Injectable} from '@angular/core'; import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '@angular/router'; import {Observable} from 'rxjs'; import {AuthService} from './auth.service'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { constructor(private authService: AuthService, private router: Router) { } canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean { return this.authService.isAuthenticated().then( (authenticated: boolean) => { if (authenticated) { return true; } else { this.router.navigate(['/']); return false; } } ); } }
auth.service.ts
import {Injectable} from '@angular/core'; @Injectable({ providedIn: 'root' }) export class AuthService { loggedIn = false; constructor() { } login() { this.loggedIn = true; } logout() { this.loggedIn = false; } isAuthenticated() { const promise = new Promise((resolve, reject) => { setTimeout(() => { resolve(this.loggedIn); }, 800); }); return promise; } }
app.module.ts
import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {FormsModule} from '@angular/forms'; import {HttpModule} from '@angular/http'; import {AppComponent} from './app.component'; import {HomeComponent} from './home/home.component'; import {UsersComponent} from './users/users.component'; import {ServersComponent} from './servers/servers.component'; import {UserComponent} from './users/user/user.component'; import {EditServerComponent} from './servers/edit-server/edit-server.component'; import {ServerComponent} from './servers/server/server.component'; import {ServersService} from './servers/servers.service'; import {RouterModule, Routes} from '@angular/router'; import {PageNotFoundComponent} from './page-not-found/page-not-found.component'; import {AuthService} from './auth.service'; import {AuthGuard} from './auth.guard'; const appRoutes: Routes = [ {path: '', 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: 'not-found', component: PageNotFoundComponent}, {path: '**', redirectTo: '/not-found'}, ]; @NgModule({ declarations: [ AppComponent, HomeComponent, UsersComponent, ServersComponent, UserComponent, EditServerComponent, ServerComponent, PageNotFoundComponent ], imports: [ BrowserModule, FormsModule, HttpModule, RouterModule.forRoot(appRoutes) ], providers: [ServersService, AuthGuard, AuthService], bootstrap: [AppComponent] }) export class AppModule { }
References
https://angular.io/guide/router#milestone-5-route-guards