Retrieve the json translation file from the server using Angular and seamlessly integrate it into the browser

I recently obtained a JSON file from the server that contains translations for handling server error messages in my frontend application. I am wondering if it would be feasible to replace an existing empty JSON file in my app with this new file, or if it would be more advisable to store it in local storage instead. What would be the most effective approach in this scenario?

Answer №1

When it comes to handling language translations on the server side, I opt for transmitting my current language to the server during login. This way, the server can respond in the client's preferred language.

If you're looking for an alternative solution, consider using ngx-translate, a powerful library that leverages Pipes to create a multi-language application with additional functionalities. You can find more information about it here.

With ngx-translate, you have the option to utilize a custom loader to load your translated texts from a specified JSON file located at a given URL. Usually, this URL points to your assets folder, but you can also fetch translations from an external link as illustrated here.

export class CustomLoader implements TranslateLoader  {
  constructor(private httpClient: HttpClient) {}
  getTranslation(lang: string): Observable<any> {
    const header = new HttpHeaders({
     'Content-Type': 'application/json',
     'Access-Control-Allow-Origin': '*',
    });
    const apiAddress = 'https://xxxx.xxx.xxxx.windows.net/lang/en.json';
    return this.httpClient.get(apiAddress, { headers: header});
  }
}

It's worth noting that the syntax has been updated slightly. Now, within the App Module, you need to utilize ngx-translate's HttpBackend instead of Angular's HttpClient. For further details, refer to the official documentation of ngx-translate.

imports: [
...
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpBackend],
      },
    }),
  ],
  providers: [],
  bootstrap: [AppComponent],
})
export class AppModule {}

function HttpLoaderFactory(http: HttpBackend) {
  return new MultiTranslateHttpLoader(http, [
    { prefix: './assets/i18n/', suffix: '.json' },
  ]);
}

For additional insights into integrating internationalization and translations in Angular, including backend integration and lazy loading, check out this informative link.

To enable translations loaded from an external API server, we must develop our custom loader that adheres to the TranslateLoader interface with the required method getTranslation() returning an Observable. The custom loader implementation can be placed in a separate file named translate-loader.ts:

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

import { environment } from '../environments/environment';

export class CustomTranslateLoader implements TranslateLoader {
  constructor(private http: HttpClient) {}

  getTranslation(lang: string): Observable<any> {
    return this.http.get(`${environment.apiHost}/translations/${lang}`);
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to exit an ASP.NET application by pressing the exit button

I am new to asp.net and currently using Visual Studio 2012. Currently, I am working on a login page where I have two buttons: Login and Exit. Whenever I click on the Exit button, I want the application to close and also stop the debugging process. I cam ...

Creating a Fixed Header and Footer in HTML When Content Exceeds a Specific Height

Imagine an HTML template with the following structure: ------------- |Header Data| ------------- | | | Main Data | | | ------------- |Footer Data| ------------- The Header Data, Main Data, and Footer Data sections have fixed height va ...

Exploring Knockout.js and ObservableArrays with the Mapping Plugin

Initially, the code below works perfectly when called for the first time. But in subsequent calls, the gridviewmodel becomes messy and duplicates all data. $.ajax({ url: 'rest service uri', type: 'GET', data: pa ...

Creating double the mesh in THREE.js by utilizing identical vectors as their position coordinates

Recently, I upgraded from r67 to r69 in ThreeJS and now facing issues with referencing the positions of objects to a single vector. Prior to the update, this code snippet worked fine: var vector = new THREE.Vector3(50, 50, 50); _Mesh1.position = vector; ...

The issue I'm facing is that json_encode includes HTML elements, causing JSON.parse to fail in

Being new to PHP and JavaScript, I recently encountered an issue when trying to encode MYSQL output in PHP that contained HTML tags. Unfortunately, the output on the JavaScript side failed to parse properly. However, upon encoding MYSQL output without HTML ...

Skipping certain key-value pairs during the conversion from JSON to Excel Worksheet using the XLSX library in JavaScript

I have a set of objects in JSON format within my JavaScript code and I am looking to transform this data into an Excel worksheet. Within the JSON structure, there are certain key-value pairs that I do not wish to include in the Excel output. For instance, ...

The attempted use of Wget with JavaScript integration was unsuccessful

Is there a way to save a dynamically generated page from the command line? I attempted to download it using: wget PageWithJS.com -O output.html However, the output.html file does not include the dynamically generated content. Any suggestions? ...

Translate array into object with correct data types (type-specific method)

Welcome In our project, we have implemented attributes support where each attribute acts as a class. These attributes include information on type, optionality, and name. Instead of creating an interface for every entity, my goal is to automate this proces ...

Exploring the Dev Tools Console feature in Excel for Windows

I have developed an Excel add-in using AngularJS. I utilize <div ng-show="isLoggedIn">...</div> and <div ng-show="!isLoggedIn">...</div> to manage different content based on the value of $scope.isLoggedIn. While it functions well i ...

The 'setParent' property is undefined and cannot be read

In my Angular 6 project, I am utilizing a reactive form which includes a table in a child component: <div formArrayName="_server"> <table id="_server" class="table table-striped table-bordered"> <thead> <tr> ...

Creating a JavaScript class that mimics the behavior of a C# class/object and can be seamlessly used in a Vue component

I am looking to develop a unique Javascript class that can be instantiated from a Vue component and have functions called on it similar to how it is done in C#. public class MyCustomClass() { public MyCustomClass(string someParameter){ .... ...

Unable to retrieve the updated value from the service variable

I'm attempting to implement a filter that allows me to search for items based on a service variable that is updated with user input. However, I am only able to retrieve the initial value from the service in my component. Service HTML (whatever is typ ...

When calling `getAuth()`, an object is returned. However, upon reloading the page, the

My code is extensive, so I have only included a portion that I believe is crucial. import {getAuth} from "firebase/auth" const authFirebase = getAuth() console.log(authFirebase) const Home = () => { ... return( ... ) } Every time I ...

Is the key to achieving optimal client interactions within a client layout, while still maintaining its role as a server component, truly possible?

My current challenge involves managing modals opening and closing with server components instead of client components. In the past, I used to lift the state up to my Layout for client components: export default function Layout({ children }) { const [showP ...

Delete the item if the link uses Javascript: void(0)

<a class="slicknav_item" href="home">Home<span></span></a> <a class="slicknav_item" href="about">About<span></span></a> <a class="slicknav_item" href="javascript: void(0)">Services<span></span& ...

Unable to retrieve elements from the eBay website using JavaScript within a Chrome extension

I recently developed a Chrome extension that scrapes all orders from an eBay orders page. It was working flawlessly last month, but suddenly I am facing issues accessing some elements. Here is the snippet of code causing trouble: let elGridComp = document ...

Angular 8 does not show the default option in the select tag

When I use the following code snippet: <div style="text-align:center"> <form> <select type="checkbox" name="vehicle1" (change)="onchange()" > <option> 1 </option> <opti ...

Can someone explain the function of statements such as (function () { // code; }.call(this)); within a JavaScript module?

By utilizing the Function.prototype.call() method, it becomes possible to create a function that can be applied to various objects. I delved into the code of , which had been minified and required to be un-minified for examination. The structure of the co ...

Angular manipulate, organize and paginate data in a table

I am currently exploring Angular5 for a web application I am working on. On one page, I require a table to display data retrieved from a Restful API endpoint, including fields like Name, Last Name, Age, Group, and others. For the frontend interface, I wou ...

Setting up the Kik Bot configuration can be a bit confusing at first

After installing @kikinteractive/kik and testing the script in /home/usersite/node_modules/, I find myself at a roadblock. How do I properly import @kikinteractive/kik? 2. Create a bot using the username and API key obtained from . 3. Follow the instruct ...