Angular 2 Authentication with child routes

前端 未结 3 1141
清酒与你
清酒与你 2020-12-09 06:30

I have an angular 2 application in which I need to be authenticated on every page. So I have implemented a custom RouterOutlet to confirm I am logged in on every page change

3条回答
  •  半阙折子戏
    2020-12-09 06:44

    Here's an updated example of using an AuthGuard with Angular 2 RC6.

    Routes with home route protected by AuthGuard

    import { Routes, RouterModule } from '@angular/router';
    
    import { LoginComponent } from './login/index';
    import { HomeComponent } from './home/index';
    import { AuthGuard } from './_guards/index';
    
    const appRoutes: Routes = [
        { path: 'login', component: LoginComponent },
    
        // home route protected by auth guard
        { path: '', component: HomeComponent, canActivate: [AuthGuard] },
    
        // otherwise redirect to home
        { path: '**', redirectTo: '' }
    ];
    
    export const routing = RouterModule.forRoot(appRoutes);
    

    AuthGuard redirects to login page if user isn't logged in

    import { Injectable } from '@angular/core';
    import { Router, CanActivate } from '@angular/router';
    
    @Injectable()
    export class AuthGuard implements CanActivate {
    
        constructor(private router: Router) { }
    
        canActivate() {
            if (localStorage.getItem('currentUser')) {
                // logged in so return true
                return true;
            }
    
            // not logged in so redirect to login page
            this.router.navigate(['/login']);
            return false;
        }
    }
    

    For the full example and working demo you can check out this post

提交回复
热议问题