As mentioned by @yurzui in the comments section, angular guards prevent views from rendering if the guard validation fails (component life cycle will not be triggered if guard fails).
Checkout this sample code snippet that you can use to add a guard for authenticated views in your application -
Guard Definition
import { Injectable } from "@angular/core";
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from "@angular/router";
@Injectable()
export class LoggedInGuard implements CanActivate {
constructor() { }
public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<any> {
return new Promise<any>((resolve: Function, reject: Function) => {
//this is where you need to validate the user
//it can be an AJAX call
let response: any;
//assuming the AJAX call is made here
//response = HttpService.getData();
//resolve indicates user is validated by the service and guard allows user to land on the reuqested view.
//reject on the other hand, will stop user from landing on requested view
//this logic can be customised.
response.success ? resolve() : reject();
});
}
}
Route Definition
import { Route } from "@angular/router";
import { HomeComponent } from "./components/home.component";
import { LoginComponent } from "./components/login.component";
export const routes: Route[] = [{
path: "route",
canActivate: [LoggedInGuard],
component: HomeComponent,
},{
path: "*",
component: LoginComponent,
}];
Do checkout this SO answer to know how to trigger multiple guards in series as it most of the times creates problems because angular doesn't fire guards in series.
I hope this helps you.