canactivate angular redirect code example
Example 1: redirect angular
import { RoleComponent } from './role/role.component';
import { AppComponent } from './app.component';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: '', redirectTo: '/AppComponent', pathMatch: 'full' },
{ path: 'role', component: RoleComponent },
];
@NgModule({
imports: [ RouterModule.forRoot(routes) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {
constructor(private router: Router)
}
functionOnWhichRedirectShouldHappen(){
router.navigate(['/role']);
}
Example 2: angular guard redirect
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (!this.authService.isLoggedIn) {
return this.router.parseUrl('/notauthorized');
} else {
return true;
}
}
}