NG0203 and NullInjectorError on Angular17 Application with Keycloak

I’m having 2 issues on with my application in the Homolog server, the first issue is the NG0203 when i have an empty cache:

ERROR RuntimeError: NG0203: inject() must be called from an core.mjs:6531 injection context such as a constructor, a factory function, a field initializer, or a function used with ‘runInInjectionContext’.

and the second issue appears at random times after i have cached some stuff from leaving the webpage open and reloading a few times:

ERROR NullInjectorError: R3InjectorError (Standalone[_AppComponent])[_AutheticationService -> _AutheticationService -> _KeycloakService -> _KeycloakService]: NullInjectorError: No provider for _KeycloakService!

And this second error indicates that it’s happening in:
authentication.service.ts:11:39 and 40:3

The first issue is “resolved” if the user keeps refreshing the page, which seems to create a cache or something.

The Second issue i have no idea why it’s happening and i’m trying to debug my code to look for the cause.

I’ll link the relevant code below:

Here’s my authenticationService code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { KeycloakService } from 'keycloak-angular';
import { inject, Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
u/Injectable({
providedIn: 'root'
})
export class AuthenticationService {
private readonly _keycloakService = inject(KeycloakService);
redirectToLoginPage(): Promise<void> {
return this._keycloakService.login();
}
get userName(): string {
return this._keycloakService.getUsername();
}
isLoggedIn(): boolean {
return this._keycloakService.isLoggedIn();
}
async getToken(): Promise<string> {
try {
return await this._keycloakService.getToken();
} catch (error) {
console.error('Error getting token', error);
throw error;
}
}
logout(): void {
this._keycloakService.logout(environment.keycloak.postLogoutRedirectUri);
}
isSessionActive(): boolean {
return !this._keycloakService.isTokenExpired();
}
}
</code>
<code>import { KeycloakService } from 'keycloak-angular'; import { inject, Injectable } from '@angular/core'; import { environment } from '../../../environments/environment'; u/Injectable({ providedIn: 'root' }) export class AuthenticationService { private readonly _keycloakService = inject(KeycloakService); redirectToLoginPage(): Promise<void> { return this._keycloakService.login(); } get userName(): string { return this._keycloakService.getUsername(); } isLoggedIn(): boolean { return this._keycloakService.isLoggedIn(); } async getToken(): Promise<string> { try { return await this._keycloakService.getToken(); } catch (error) { console.error('Error getting token', error); throw error; } } logout(): void { this._keycloakService.logout(environment.keycloak.postLogoutRedirectUri); } isSessionActive(): boolean { return !this._keycloakService.isTokenExpired(); } } </code>
import { KeycloakService } from 'keycloak-angular';

import { inject, Injectable } from '@angular/core';

import { environment } from '../../../environments/environment';

u/Injectable({
  providedIn: 'root'
})
export class AuthenticationService {
  private readonly _keycloakService = inject(KeycloakService);

  redirectToLoginPage(): Promise<void> {
    return this._keycloakService.login();
  }

  get userName(): string {
    return this._keycloakService.getUsername();
  }

  isLoggedIn(): boolean {
    return this._keycloakService.isLoggedIn();
  }

  async getToken(): Promise<string> {
    try {
      return await this._keycloakService.getToken();
    } catch (error) {
      console.error('Error getting token', error);
      throw error;
    }
  }

  logout(): void {
    this._keycloakService.logout(environment.keycloak.postLogoutRedirectUri);
  }

  isSessionActive(): boolean {
    return !this._keycloakService.isTokenExpired();
  }
}

And here’s my Keycloak Initialization:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { KeycloakService } from 'keycloak-angular';
import { provideHttpClient, withFetch } from '@angular/common/http';
import { APP_INITIALIZER, ApplicationConfig } from '@angular/core';
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
import { provideRouter } from '@angular/router';
import { environment } from '../environments/environment';
import { routes } from './app.routes';
export const initializeKeycloak = (keycloak: KeycloakService) => async () => {
try {
await keycloak.init({
config: {
url: environment.keycloak.authority,
realm: environment.keycloak.realm,
clientId: environment.keycloak.clientId,
},
loadUserProfileAtStartUp: true,
initOptions: {
checkLoginIframe: false,
onLoad: 'check-sso',
redirectUri: environment.keycloak.redirectUri,
scope: 'openid',
},
enableBearerInterceptor: true
});
} catch (error) {
console.error('Keycloak initialization failed:', error);
throw error;
}
};
export const appConfig: ApplicationConfig = {
providers: [
KeycloakService,
{
provide: APP_INITIALIZER,
useFactory: initializeKeycloak,
multi: true,
deps: [KeycloakService],
},
provideRouter(routes),
provideAnimationsAsync(),
provideHttpClient(withFetch()),
],
};
</code>
<code>import { KeycloakService } from 'keycloak-angular'; import { provideHttpClient, withFetch } from '@angular/common/http'; import { APP_INITIALIZER, ApplicationConfig } from '@angular/core'; import { provideAnimationsAsync } from '@angular/platform-browser/animations/async'; import { provideRouter } from '@angular/router'; import { environment } from '../environments/environment'; import { routes } from './app.routes'; export const initializeKeycloak = (keycloak: KeycloakService) => async () => { try { await keycloak.init({ config: { url: environment.keycloak.authority, realm: environment.keycloak.realm, clientId: environment.keycloak.clientId, }, loadUserProfileAtStartUp: true, initOptions: { checkLoginIframe: false, onLoad: 'check-sso', redirectUri: environment.keycloak.redirectUri, scope: 'openid', }, enableBearerInterceptor: true }); } catch (error) { console.error('Keycloak initialization failed:', error); throw error; } }; export const appConfig: ApplicationConfig = { providers: [ KeycloakService, { provide: APP_INITIALIZER, useFactory: initializeKeycloak, multi: true, deps: [KeycloakService], }, provideRouter(routes), provideAnimationsAsync(), provideHttpClient(withFetch()), ], }; </code>
import { KeycloakService } from 'keycloak-angular';

import { provideHttpClient, withFetch } from '@angular/common/http';
import { APP_INITIALIZER, ApplicationConfig } from '@angular/core';
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
import { provideRouter } from '@angular/router';

import { environment } from '../environments/environment';
import { routes } from './app.routes';

export const initializeKeycloak = (keycloak: KeycloakService) => async () => {
  try {
    await keycloak.init({
      config: {
        url: environment.keycloak.authority,
        realm: environment.keycloak.realm,
        clientId: environment.keycloak.clientId,
      },
      loadUserProfileAtStartUp: true,
      initOptions: {
        checkLoginIframe: false,
        onLoad: 'check-sso',
        redirectUri: environment.keycloak.redirectUri,
        scope: 'openid',
      },
      enableBearerInterceptor: true
    });
  } catch (error) {
    console.error('Keycloak initialization failed:', error);
    throw error;
  }
};

export const appConfig: ApplicationConfig = {
  providers: [
    KeycloakService,
    {
      provide: APP_INITIALIZER,
      useFactory: initializeKeycloak,
      multi: true,
      deps: [KeycloakService],
    },
    provideRouter(routes),
    provideAnimationsAsync(),
    provideHttpClient(withFetch()),
  ],
};

Main.ts

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import { registerLocaleData } from '@angular/common';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import localePt from '@angular/common/locales/pt';
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter, withViewTransitions } from '@angular/router';
import { AppComponent } from './app/app.component';
import { appConfig } from './app/app.config';
import { routes } from './app/app.routes';
import { keycloakHttpInterceptor } from './app/interceptor/keycloak-http.interceptor';
registerLocaleData(localePt, 'pt-BR');
bootstrapApplication(AppComponent, {
providers: [
...appConfig.providers,
provideHttpClient(withInterceptors([keycloakHttpInterceptor])),
provideRouter(routes, withViewTransitions())
]
}).catch(err => {
console.error('Application bootstrapping failed:', err);
});
</code>
<code>import { registerLocaleData } from '@angular/common'; import { provideHttpClient, withInterceptors } from '@angular/common/http'; import localePt from '@angular/common/locales/pt'; import { bootstrapApplication } from '@angular/platform-browser'; import { provideRouter, withViewTransitions } from '@angular/router'; import { AppComponent } from './app/app.component'; import { appConfig } from './app/app.config'; import { routes } from './app/app.routes'; import { keycloakHttpInterceptor } from './app/interceptor/keycloak-http.interceptor'; registerLocaleData(localePt, 'pt-BR'); bootstrapApplication(AppComponent, { providers: [ ...appConfig.providers, provideHttpClient(withInterceptors([keycloakHttpInterceptor])), provideRouter(routes, withViewTransitions()) ] }).catch(err => { console.error('Application bootstrapping failed:', err); }); </code>
import { registerLocaleData } from '@angular/common';
import { provideHttpClient, withInterceptors } from '@angular/common/http';
import localePt from '@angular/common/locales/pt';
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter, withViewTransitions } from '@angular/router';

import { AppComponent } from './app/app.component';
import { appConfig } from './app/app.config';
import { routes } from './app/app.routes';
import { keycloakHttpInterceptor } from './app/interceptor/keycloak-http.interceptor';

registerLocaleData(localePt, 'pt-BR');

bootstrapApplication(AppComponent, {
  providers: [
    ...appConfig.providers,
    provideHttpClient(withInterceptors([keycloakHttpInterceptor])),
    provideRouter(routes, withViewTransitions())
  ]
}).catch(err => {
  console.error('Application bootstrapping failed:', err);
});

Any help understanding the issue is appreciated, Thanks in advance.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật