Home > Software engineering >  redirect to login page if user not logged in angular 12
redirect to login page if user not logged in angular 12

Time:09-27

I am Using Angular 12 I need to redirect to login page if user tried to access page must be authenticated to access it I tried to use this but I failed I used gurd

admin.gurd.ts

  export class AdminGuard implements CanActivate {
  constructor(private accountService: AccountService, private toastr:ToastrService,private router:Router) { }

  canActivate(): Observable<boolean>{
    return this.accountService.currentUser$.pipe(
      map((user:User)=>{
        if (!user.role.includes('Administrator') || !user.role.includes('Customer') || !user.role.includes('Seller'))return true;
        this.router.navigate(['/']);
        this.toastr.error("You Not Allowed To Enter Here")
        return false;
      })
    )
  }

}

app-routing.moudle.ts

const routes: Routes = [
  {
    path: 'controlPanel', component: MainComponent,canActivate:[AdminGuard],
    children:[
      {path: '', component: HomeComponent}
    ]
  },
  {path: 'login', component: LoginComponent},
  {path: '', component: LoginComponent},
  {path: '**', redirectTo: '', pathMatch: 'full'},
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

CodePudding user response:

You can update 'admin.gurd.ts' file with the below code

export class AdminGuard implements CanActivate {
  constructor(private accountService: AccountService, private toastr:ToastrService,private router:Router) { }

  canActivate(): Observable<boolean>{
    return this.accountService.currentUser$.pipe(
      map((user:User)=>{
        if (!user.role.includes('Administrator') || !user.role.includes('Customer') || !user.role.includes('Seller'))return true;         
        this.toastr.error("You Not Allowed To Enter Here")
        // Updated Line
        this.router.navigateByUrl('/login'));
        return false;
      })
    )
  }

}

CodePudding user response:

The observable returned from the guards canActivate must complete for Angular to trigger the guard. You can complete it with take(1)

canActivate(): Observable<boolean>{
    return this.accountService.currentUser$.pipe(
      map((user:User)=>{
        // add the logic
      }),
      take(1)
    )
  }
  • Related