我在 Angular 15 应用程序的 ngx-translate 和 transloco 上都遇到了这个问题,所以这可能是配置问题。
加载我的应用程序时,在
app.component.ts
中,根据用户是否登录,他将被重定向到登录组件或我配置的经过身份验证的路由。两者都是延迟加载的模块。
加载页面上的翻译没有显示(甚至没有翻译键)。
在经过身份验证的路线上,当我刷新时,只有在刷新或更改语言后才会加载翻译。
这只会在我尝试使用默认语言时发生。
这是我的配置:
transloco-root.module.ts
@Injectable({ providedIn: 'root' })
export class TranslocoHttpLoader implements TranslocoLoader {
constructor(private http: HttpClient) {}
getTranslation(lang: string) {
return this.http.get<Translation>(`/assets/i18n/${lang}.json`);
}
}
@NgModule({
exports: [TranslocoModule],
providers: [
{
provide: TRANSLOCO_CONFIG,
useValue: translocoConfig({
availableLangs: ['en', 'fr'],
defaultLang: 'en',
// Remove this option if your application doesn't support changing language in runtime.
reRenderOnLangChange: true,
prodMode: environment.production,
}),
},
{ provide: TRANSLOCO_LOADER, useClass: TranslocoHttpLoader },
],
})
export class TranslocoRootModule {}
app.module.ts
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
BrowserAnimationsModule,
BrowserModule,
HttpClientModule,
MatIconModule,
MatSnackBarModule,
CoreModule,
ModulesModule,
SharedModule,
StoreModule.forRoot({}),
EffectsModule.forRoot(),
StoreDevtoolsModule.instrument({
maxAge: 25, // Retains last 25 states
logOnly: !isDevMode(), // Restrict extension to log-only mode
autoPause: true, // Pauses recording actions and state changes when the extension window is not open
trace: false, // If set to true, will include stack trace for every dispatched action, so you can see it in trace tab jumping directly to that part of code
traceLimit: 75, // maximum stack trace frames to be stored (in case trace option was provided as true)
}),
TranslocoRootModule,
],
providers: [{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }],
bootstrap: [AppComponent],
})
export class AppModule {}
app.component.ts
ngOnInit(): void {
if (authenticated) {
...
this.router.navigate(['customers']);
} else {
this.router.navigate(['login']);
}
}
login.module.ts
@NgModule({
declarations: [LoginComponent],
imports: [CommonModule, LoginRoutingModule, TranslocoModule],
exports: [LoginComponent],
})
export class LoginModule {}
login.component.html
<div id="sign-in-btn" class="sign-in">
<button (click)="this.redirect()">{{ 'LOGIN.SIGN_IN' | transloco }}</button>
</div>
我试图强制加载语言并在
transloco.load('en').subscribe(() => this.router.navigate(['login']);
之后重定向,但它从不重定向。我查看了请求,en.json
文件从未加载过。
我也尝试过使用
APP_INITIALIZER
但没有用。