简体   繁体   English

如何在ngx-translate中将TranslateHttpLoader与服务URL一起使用

[英]How to use TranslateHttpLoader with service url in ngx-translate

I am trying to get translated text from content management system with service URL. 我正在尝试从具有服务URL的内容管理系统中获取翻译的文本。 When I use a JSON file it works well, but how can I use a service URL to get translated data? 当我使用JSON文件时,它运作良好,但是如何使用服务URL来获取转换后的数据?

This is the code that's not working: 这是无效的代码:

export function createTranslateLoader(http: Http) {
  return new TranslateHttpLoader(http, 'http://test.test.com/test/test/Translations/{lang}/{SiteId}');
}    

Yesterday I have faced the same issue on how to make use of JSON response from API calls using ngx-translate and I have identified the solution. 昨天,我在使用ngx-translate如何利用API调用的JSON响应时遇到了同样的问题,并且已经找到了解决方案。 I know its very late to update here, but I believe some one will get benefit out of it. 我知道在这里更新很晚,但是我相信会有人从中受益。

Ngx-translate offers to use Service if you are not going to use .json file. 如果您不打算使用.json文件,则Ngx-translate可以使用Service。 For this, in your *.module.ts file, "useClass" instead of "useFactory" like below. 为此,在您的* .module.ts文件中,使用“ useClass”代替“ useFactory”,如下所示。

 @NgModule({
      imports: [SharedModule, SharedComponentsModule, routing,
        TranslateModule.forRoot({
          loader: {
            provide: TranslateLoader,
            useClass: TranslationService,
            //useFactory : HttpLoaderFactory,
            deps: [HttpClient]
          }

In your Translation Service, just make call of API url something like this. 在您的翻译服务中,只需调用API网址即可。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { TranslateLoader } from '@ngx-translate/core';

@Injectable()
export class TranslationService implements TranslateLoader {

    constructor(private http: HttpClient) { }

    getTranslation(lang: string): Observable<any> {
    return this.http.get(`http://<someurlreferences>?language=${lang}`)
    .map((response: JSON) => {
    return response;
    });
    }   
}

Remember: The API response should be in JSON format. 切记:API响应应为JSON格式。 Else, ngx-translate would not translate. 否则,ngx-translate不会翻译。

Assuming your JSON response is in below Format 假设您的JSON响应采用以下格式

{
    "Data": {
        "First": [{
            "key": "FirstKey",
            "value": "FirstValue"
        }]
    }
}

Then, in your *.component.ts file 然后,在您的* .component.ts文件中

import { Component, OnInit } from '@angular/core'
import { TranslateService } from '@ngx-translate/core';

@Component({
  template: `<button (click)="switchLanguage('en')" >English</button>
            <button (click)="switchLanguage('cy')" >Welsh</button>
             <h1>{{'Data.First.0.value' | translate }} <!--FirstValue--> 
                    </h1>`

export class SomeComponent implements OnInit {
constructor(private translate: TranslateService) {
      translate.addLangs(['en', 'cy']);
      translate.setDefaultLang('en');

      const browserLang = translate.getBrowserLang();
      translate.use(browserLang.match(/en|cy/) ? browserLang : 'en');
     }
    switchLanguage(language: string) {
    this.translate.use(language);
  }
}

The UI displays two buttons (English and Welsh) and on clicking, the service API url will be called based on language parameter accordingly. 用户界面显示两个按钮(英语和威尔士语),单击后,将根据语言参数相应地调用服务API网址。

I ran into the same issue when trying to move from 'assets/i18n/english.json' etc to MySQL database for fetching the translated values dynamically from a table. 我试图从'assets / i18n / english.json'等移动到MySQL数据库以从表中动态获取转换后的值时遇到了相同的问题。 I wanted to do this so that the admin can change them on his own. 我想这样做,以便管理员可以自己更改它们。

So, I tried the answer given by Viswa and it works but I found a simpler way of doing this HttpLoaderFactory. 因此,我尝试了Viswa给出的答案,它可以工作,但是我找到了一种执行HttpLoaderFactory的简单方法。 Just add the following to your app.module.ts. 只需将以下内容添加到您的app.module.ts中。 Replace the URL with your API. 用您的API替换URL。 Mine was like ' http://localhost:8080/translation/:language ' 我的感觉就像是' http:// localhost:8080 / translation /:language '

export function HttpLoaderFactory(http: HttpClient) {  
  return new TranslateHttpLoader(http, "http://localhost:8080/translation/", "");
}

Another thing that wasted some time as I was sending an array of objects like [{name: 'Name'}] instead of sending just an object like {name: 'Name'} . 另一件事浪费了一些时间,因为我发送的是[{name: 'Name'}]的对象数组,而不是仅仅发送{name: 'Name'}类的对象。 Once that was fixed, it worked like a charm! 一旦修复,它就像一个魅力!

Your approach is absolutely correct. 您的方法是绝对正确的。 But that creates another problem. 但这带来了另一个问题。 We cannot keep the language fetch URL static in HttpLoaderFactory. 我们无法在HttpLoaderFactory中将语言获取URL保持为静态。 It may be dynamic some time. 有时可能是动态的。 And the solution provided by Viswa is for dynamic URL. Viswa提供的解决方案是针对动态URL的。 Using service we can provide the dynamic URL to fetch the translated language from the database. 使用服务,我们可以提供动态URL,以从数据库中获取翻译的语言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM