If you define that in for example AppComponent you will receive evens for example of type: OnTokenExpired to refresh automatically your token, but not he event OnAuthSuccess because this subsciption is made after the login so the last event never be triggered. I'm trying to workaround this problem know by the keycloak-angular guys.
A sample of that could be:
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { KeycloakService, KeycloakEvent, KeycloakEventType } from 'keycloak-angular';
import { KeycloakProfile } from 'keycloak-js';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
public title: String = 'Productland Portal';
public isLoggedIn = false;
public userProfile: KeycloakProfile | null = null;
constructor(private readonly keycloakService: KeycloakService,
private readonly router: Router,) {
// configure token expiration handler
keycloakService.keycloakEvents$.subscribe({
next: (event: KeycloakEvent) => {
if (event.type == KeycloakEventType.OnAuthSuccess) {
this.router.navigateByUrl('/');
}
else if (event.type == KeycloakEventType.OnTokenExpired) {
console.log('Token refreshed at ' + new Date());
keycloakService.updateToken(20);
}
else if (event.type == KeycloakEventType.OnAuthRefreshError) {
this.router.navigateByUrl('/');
}
}
});
}
}