You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 17中Transloco无法加载翻译的问题求助

Angular 17 中使用 Transloco 无法渲染翻译文本问题

我在Angular 17中使用Transloco,按照文档尝试在模板中通过结构指令翻译简单文本:

<ng-container *transloco="let t"> 
  <h2>{{ t('greeting') }}</h2> 
</ng-container>

但完全没有文本被渲染出来,且网络面板中没有Http请求,说明翻译文件未被获取。我已经尝试过使用相对路径和绝对路径指向翻译文件,仍未解决。

完整代码如下:

main.ts

import { Component, inject, isDevMode } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import { provideHttpClient } from '@angular/common/http';
import { TranslocoHttpLoader } from './transloco-loader';
import { TranslocoService, provideTransloco } from '@jsverse/transloco';

@Component({
  selector: 'app-root',
  standalone: true,
  template: `
    <ng-container *transloco="let t">
      <h2>{{ t('greeting') }}</h2>
    </ng-container>
    <button (click)="onChangeToSpanish()">Change to Spanish</button>
  `,
})
export class App {
  private translocoService = inject(TranslocoService);

  onChangeToSpanish() {
    this.translocoService.setActiveLang('es');
  }
}

bootstrapApplication(App, {
  providers: [
    provideHttpClient(),
    provideTransloco({
      config: {
        availableLangs: ['en', 'es'],
        defaultLang: 'en',
        // Remove this option if your application doesn't support changing language in runtime.
        reRenderOnLangChange: true,
        prodMode: !isDevMode(),
      },
      loader: TranslocoHttpLoader,
    }),
  ],
});

transloco-loader.ts

import { inject, Injectable } from '@angular/core';
import { Translation, TranslocoLoader } from '@jsverse/transloco';
import { HttpClient } from '@angular/common/http';

@Injectable({ providedIn: 'root' })
export class TranslocoHttpLoader implements TranslocoLoader {
  private http = inject(HttpClient);

  getTranslation(lang: string) {
    return this.http.get<Translation>(`/assets/i18n/${lang}.json`);
  }
}

按道理这是常规流程,我感觉自己遗漏了某些步骤,希望得到帮助。

内容的提问来源于stack exchange,提问作者codrut

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 07:03:13