Angular2: Prevent authenticated users from accessing specific routes

后端 未结 3 1334
礼貌的吻别
礼貌的吻别 2020-12-31 04:43

I\'ve defined some routes in my main.ts file:

const routes: RouterConfig = [
  { path: \'\', component: HomeComponent },
  { path:          


        
3条回答
  •  一整个雨季
    2020-12-31 05:05

    Make ts file name auth.guard.ts put following code on that

    Write guard code

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

    Add bellow code in your routing ts file

    app-routing.module.ts

    {
          path: 'user', component: UserComponent,canActivate: [AuthGuard] ,
          children: [{ path: 'home', component: HomeComponent },
                     { path: 'view/:id', component: UserViewComponent },
                     { path: 'add', component: UserAddComponent },
                     { path: 'edit/:id', component: UserAddComponent }
                    ]  
      },
    

    Add providers in your app.module.ts file

    app.module.ts

    @NgModule({
      declarations: [
        AppComponent
        --------
      ],
      imports: [
        BrowserModule
        --------
      ],
      providers: [      
        AuthGuard        
      ],
      bootstrap: [AppComponent]
    })
    

提交回复
热议问题