Angular Transloco能否在同一read中定义两个scope?
解决Transloco在同一HTML中读取多个Scope的问题
Transloco的*transloco指令的read属性本身不支持同时指定多个scope,它仅接受单个字符串路径,所以你尝试的read: 'scope1', 'scope2'写法既不符合语法要求,也无法实现预期效果。以下是几种可行的替代方案:
1. 组件中通过TranslocoService合并多Scope翻译
在组件类中利用TranslocoService的selectTranslation方法分别获取两个scope的翻译对象,再合并后供模板使用:
import { Component } from '@angular/core'; import { TranslocoService } from '@ngneat/transloco'; import { combineLatest, map } from 'rxjs'; @Component({ selector: 'app-your-component', templateUrl: './your-component.component.html' }) export class YourComponent { combinedTranslations$ = combineLatest([ this.translocoService.selectTranslation('scope1'), this.translocoService.selectTranslation('scope2') ]).pipe( // 合并两个scope的翻译对象,若存在重复键,后一个scope的键会覆盖前一个 map(([scope1Trans, scope2Trans]) => ({ ...scope1Trans, ...scope2Trans })) ); constructor(private translocoService: TranslocoService) {} }
模板中通过async管道使用合并后的翻译:
<div class="fr-container" *ngIf="combinedTranslations$ | async as t"> {{ t.yourKeyFromScope1 }} {{ t.yourKeyFromScope2 }} </div>
2. 模板中单独指定Scope读取翻译
如果不需要合并所有键,可在模板中针对不同内容分别指定read属性:
使用*transloco指令
<div class="fr-container"> <p *transloco="let t; read: 'scope1'">{{ t.greeting }}</p> <p *transloco="let t; read: 'scope2'">{{ t.buttonLabel }}</p> </div>
使用transloco管道
<div class="fr-container"> {{ 'greeting' | transloco: {} : 'scope1' }} {{ 'buttonLabel' | transloco: {} : 'scope2' }} </div>
3. 静态合并Scope(适合固定场景)
如果两个scope的内容是固定且常用的,可以通过自定义加载器或配置,将两个scope的翻译文件合并为一个新的scope,之后就能直接在read中使用这个合并后的scope:
// transloco-root.module.ts import { HttpClient } from '@angular/common/http'; import { TranslocoHttpLoader } from './transloco-loader'; import { TranslocoModule } from '@ngneat/transloco'; import { combineLatest, map } from 'rxjs'; export function translocoLoader(http: HttpClient) { return new CustomTranslocoLoader(http); } class CustomTranslocoLoader extends TranslocoHttpLoader { override getTranslation(lang: string) { // 同时加载两个scope的翻译文件并合并 return combineLatest([ this.http.get(`/assets/i18n/${lang}/scope1.json`), this.http.get(`/assets/i18n/${lang}/scope2.json`) ]).pipe( map(([scope1, scope2]) => ({ ...scope1, ...scope2 })) ); } } @NgModule({ imports: [ TranslocoModule.forRoot({ loader: translocoLoader, defaultLang: 'en' }) ] }) export class TranslocoRootModule {}
之后在模板中就可以直接读取合并后的内容(这里相当于把合并后的内容作为全局翻译,或者你也可以将其命名为新的scope):
<div class="fr-container" *transloco="let t"> {{ t.keyFromScope1 }} {{ t.keyFromScope2 }} </div>
内容的提问来源于stack exchange,提问作者Damian
相关产品推荐
相关产品推荐

