在不重新加载页面的情况下从外部内容源加载语言文件时向 Ngx-Translate 添加查询字符串

Adding a querystring to Ngx-Translate When Loading Language Files from External Content Sources Without Page Reload

我正在使用 ngx-translate 来管理 Angular 12 中的国际化,我正在使用 API 来检索我的语言文件,它工作正常,但我不确定如何将附加参数传递给 API 以执行附加逻辑来决定正确的语言文件。

这是我当前的设置: 在我的 app.module.ts

.
.
.

    imports: [
        BrowserModule,
        AppRoutingModule,
        HttpClientModule,
        TranslateModule.forRoot({
            loader: {
                provide: TranslateLoader,
                useFactory: HttpLoaderFactory,
                deps: [HttpClient]
            }
        })
      ]
.
.
.

export function HttpLoaderFactory(httpClient: HttpClient) {
  return new TranslateHttpLoader(
    httpClient,
    'http://translation-service.remote.com/',
    ''
  );
}

你可以看到我正在调用一个远程端点 http://translation-service.remote.com/ 它将 return 给我的语言 json 文件

这是我 app.component.ts

中的内容
    export class AppComponent {
  constructor(public translate: TranslateService){
    translate.addLangs(['en-us', 'en-gb']);
    translate.setDefaultLang(`en-us`);
  }
}

最后来自我的 app.component.html

   <select #langSelect (change)="translate.use(langSelect.value)">
      <option *ngFor="let lang of translate.getLangs()" [value]="lang" [selected]="lang === translate.currentLang">{{lang }}</option>
    </select>

当应用程序加载或用户选择一种语言时,ngx-translate 会发送一个如下所示的请求:http://translation-service.remote.com/[select-language] (e.g. http://translation-service.remote.com/en-us)

现在,我希望能够将查询字符串参数传递给翻译 api GET 请求。例如:http://translation-service.remote.com/en-us?extraParam=abc 无需重新加载页面,但我找不到实现它的方法。

您可以通过创建自定义 TranslateLoader 来代替 TranslateHttpLoader 来实现这一点,然后处理其中的任何自定义行为,如下所示:

export function HttpLoaderFactory(
  httpClient: HttpClient,
  helperService: HelperService
) {
  return new CustomTranslateHttpLoader(httpClient, helperService);
}

export class CustomTranslateHttpLoader implements TranslateLoader {
  constructor(private http: HttpClient, private helperService: HelperService) {}

  getTranslation(lang: string): Observable<any> {
    // Fetch the translations from the server if the extraParam is provided, otherwise return empty object.
    if (this.helperService.extraParam) {
      return this.http.get(
        `http://translation-service.remote.com/${lang}?extraParam=${this.helperService.extraParam}`
      );
    } else return of({});
  }
}

// Your module
@NgModule({
  imports: [
    TranslateModule.forChild({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient, HelperService],
      },
    }),
  ],
})

其中 HelperService 是可用于将 extraParam 传递给 CustomTranslateHttpLoader 的服务:

@Injectable({ providedIn: 'root' })
export class HelperService {
  extraParam = 'abc';
}

并且在您的组件中,您可以像下面这样处理语言更改:

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.scss'],
})
export class MyComponent {
  constructor(
    private translateService: TranslateService,
    private helperService: HelperService
  ) {}

  onLangChanged(lang: string) {
    // change the extraParam that will be used within CustomTranslateHttpLoader's getTranslation:
    this.helperService.extraParam = 'YOUR_EXTRA_PARAM_HERE';

    // Reset the selected language, and delete the inner translation, to be loaded again once `use` function is called:
    this.translateService.resetLang(lang);

    // Use the selected lang, which will cause the CustomTranslateHttpLoader to load the translation again because the `lang` is reset above.
    this.translateService.use(lang);
  }
}