Reputation: 51
I want to render another template when the authentication failed:
@Component({
selector: 'app-root',
templateUrl: './a.html',
})
export class AppComponent implements OnInit {
ngOnInit() {
if (!this.isAuthenticated()) {
this.templateUrl = './b.html';
}
}
isAuthenticated(): boolean {
// return by user authenticate status
}
}
Upvotes: 0
Views: 68
Reputation: 5039
What you need is actually a guard and not a redirection or another component.
Create an authentication.guard.ts containing this code:
@Injectable()
export class AuthenticationGuard implements CanActivate {
constructor(
private router: Router,
private authenticationService: AuthenticationService,
) {}
public canActivate(): boolean {
if (this.authenticationService.isLoggued()) {
return true;
}
this.router.navigate(["/login"]);
return false;
}
}
In your Route definition, specify that the access to a defined component should be protected by this guard:
{ path: "yourRoute", component: DummyComponent, canActivate: [AuthenticationGuard] },
Now every request will be "checked" with this guard. And you are good to go.
Upvotes: 1