我正在使用 SSR 开发 Angular 应用程序,并且正在尝试将我的项目升级到 Angular 19。我正在使用新的 keycloak-Angular ProvideKeycloak 进行身份验证。 我当前的配置在浏览器环境中运行良好,但在 SSR 环境中运行时遇到问题,因为窗口在服务器上不可用。
这是我当前的应用程序配置:
import { ApplicationConfig } from '@angular/core';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { provideClientHydration } from '@angular/platform-browser';
import { provideHttpClient, withFetch } from '@angular/common/http';
import { provideKeycloak } from 'keycloak-angular';
import { environment } from './environments/environment';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes, withComponentInputBinding()),
provideClientHydration(),
provideHttpClient(withFetch()),
provideKeycloak({
config: environment.keycloak,
initOptions: {
onLoad: 'check-sso',
silentCheckSsoRedirectUri: `${window.location.origin}/silent-check-sso.html`
}
})
]
};
问题:
不幸的是,官方升级页面上没有任何关于SSR的信息:https://github.com/mauriciovigolo/keycloak-angular/blob/main/docs/migration-guides/v19.md
您必须在 github 上提出问题以获得对 Angular SSR 的官方支持。这是长期的解决方案。
作为临时解决方法,您可以尝试以下配置。我建议这样做,直到 keycloak-Angular 团队修复该软件包以支持 SSR。
import {
ApplicationConfig,
mergeApplicationConfig,
provideZoneChangeDetection,
} from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import {
provideClientHydration,
withEventReplay,
} from '@angular/platform-browser';
import { provideKeycloak } from 'keycloak-angular';
export const browserOnlyConfig = {
providers: [
provideKeycloak({
config: {
url: 'keycloak-server-url',
realm: 'realm-id',
clientId: 'client-id',
},
initOptions: {
onLoad: 'check-sso',
silentCheckSsoRedirectUri:
typeof window !== 'undefined'
? window?.location?.origin + '/silent-check-sso.html'
: '',
},
}),
],
};
export const commonConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
provideClientHydration(withEventReplay()),
],
};
export const appConfig = mergeApplicationConfig(
commonConfig,
browserOnlyConfig
);
import { mergeApplicationConfig, ApplicationConfig } from '@angular/core';
import { provideServerRendering } from '@angular/platform-server';
import { commonConfig } from './app.config';
const serverConfig: ApplicationConfig = {
providers: [provideServerRendering()],
};
export const config = mergeApplicationConfig(commonConfig, serverConfig);
cd test
-> npm i
-> npm run start