【问题标题】:Adding a querystring to Ngx-Translate When Loading Language Files from External Content Sources Without Page Reload从外部内容源加载语言文件而不重新加载页面时向 Ngx-Translate 添加查询字符串
【发布时间】:2021-11-03 10:36:45
【问题描述】:

我正在使用 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/ 它将返回给我语言 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](例如http://translation-service.remote.com/en-us

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

【问题讨论】:

    标签: angular ngx-translate


    【解决方案1】:

    您可以通过创建自定义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);
      }
    }
    

    【讨论】:

    • 感谢您回答 Amer。我是 Angular 的新手,所以我想知道我是否能够从 UI 中读取“extraParam”?说我想根据用户选择将其更改为组合框...您共享的代码不是将执行一次吗,是模块吗?
    • 你能解释一下这个用例的整个场景吗?所以我可以让我的回答更有帮助。谢谢。
    • UI 上的用户选择了一种语言,同时也选择了一个环境名称。将使用这两个参数从服务器获取翻译。这就是为什么我需要确保两者都会被发送,而不仅仅是语言
    • 谢谢,我以为一开始不会有任何加载的语言。无论如何,仅使用reloadLang 不会更改translateService.currentLang 属性,该属性用于在调用instant/get 函数或translate 管道时获取翻译。所以调用resetLang 函数,然后调用use 函数,在你的情况下会比只使用reloadLang 更好。请检查一下,如果您觉得可以,请告诉我。
    • 确实,非常感谢,我切换到 (resetLan & use) 组合
    猜你喜欢
    • 2012-06-13
    • 2021-06-09
    • 1970-01-01
    • 1970-01-01
    • 2018-01-30
    • 2018-04-15
    • 2023-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多