hesham shawky
hesham shawky

Reputation: 1151

ngx translate angular 7 how to translate dynamic data comes from differents API's

I'm facing a problem with ngx-translate! That's is I have 2 sperate API's with different languages so for example similar to this http://example.com/api and http://example.com/fr/api/

Now in ngx-translate I have to use en/fr.json files to translate my angular application! as I saw from the docs!

But now I need be using the data that comes from the both API's! it's already translated on the server!

http://example.com/api

http://example.com/fr/api/

So my question here how I do that?! as well keep using the json files as there some statics words in my app like the application menu

If there any other alternatives please don't hesitate to tell!

Upvotes: 0

Views: 3396

Answers (2)

paras shah
paras shah

Reputation: 889

use translate pipe for only those words (some statics words in my app like the application menu)

like

{{ 'HOME.NAME' | translate }}

and remove translate filter from api data

Upvotes: 0

Jota.Toledo
Jota.Toledo

Reputation: 28434

Assumptions:

  • Only 2 possible lang options: ["en","fr"]
  • Translations files are not fetched from the localized APIs. Instead, they reside in your project´s assets folder.
  • On language change through ngx-translate, there is no need to re fetch data

You can create a service that constructs the correct API endpoint as follows:

@Injectable()
export class EnpointLocalizer {
  private readonly tokenMap = {'en': '/', '/fr/'}
  constructor(private readonly translate: TranslateService){}

  localizeJoin(sections: string[]){
   const {currentLang} = this.translate;
   return sections.join(this.tokenMap[currentLang] || '/'); 
  }
}

Then you could inject it where required and consume it as follows:

@Injectable()
export class FooService {
 private endpoint = ["http://example.com","api"];

 constructor(private http: HttpClient, private localizer: EnpointLocalizer){}

 fetch(){
   return this.http.get(this.localizer.localizeJoin(this.endpoint),...);
 }
}

Of course, there are different ways that you could implement that "localize" logic (eg. regex patter + replace). But for your use case I think this is a simple and clear start.

Upvotes: 1

Related Questions