Utilizing ngx-translate in Angular6 to dynamically load translations by making an API request to the backend

Using ngx-translate in my frontend, I aim to dynamically load translations upon app launch.

The backend delivers a response in JSON format, for example:

{
   "something: "something"
}

Instead of utilizing a local en.json file, I desire to integrate this output into my TranslateLoader.

Is there a method to accomplish this?

In summary, I wish to access '' to receive a JSON response containing the translations and then load it using TranslateHttpLoader.

Answer №1

To simplify the process, you can establish a factory like this:

export function translatorFactory(httpClient: HttpClient) {
  return new TranslateHttpLoader(httpClient, "http://localhost:xxxx/api/translation/", "");
}

Then include it in your @NgModule imports like so:

TranslateModule.forRoot({
  loader: {
    provide: TranslateLoader,
    useFactory: translatorFactory,
    deps: [HttpClient]
  }
}),

Answer №2

One way to accomplish this is by utilizing the TranslateLoader provider in conjunction with a Custom Loader Class

Within the Module:

export class CustomLoader implements TranslateLoader {

  constructor(private http: Http) {}

  public getTranslation(lang: String): Observable<any> {
    return this.http.get(URL).map(
      (res: any) => {
        return res;
      }
    );

  }
}

@NgModule({
  imports: [
    TranslateModule.forRoot({
      provide: TranslateLoader,
      useClass: CustomLoader,
      // useFactory: (createTranslateLoader),
      deps: [Http]
    })
  ]
}) 

Within the Component:

constructor(private _translate: TranslateService){}

 const transText = this._translate.instant('something');

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

The presence of HttpInterceptor within a component is causing a ripple effect on all of the App

I am encountering an issue with a library I have that includes a component. This component has an HttpInterceptor that adds a header to each of its requests. The problem arises when I use the component in another project - the HttpInterceptor ends up addi ...

Is it possible to create a distinctive property value within an ngFor loop that operates autonomously across two child components?

I am working on a functionality where, upon clicking on a specific car brand, the name of the person and their favorite car will be displayed at the bottom. However, I'm facing an issue where the car brand is being repeated among all items in the ngFo ...

Tips for adjusting the maximum characters per line in tinyMCE 5.0.11

I have an angular 8 application that utilizes tinyMCE, and I am looking to limit the maximum number of characters per line in the textArea of tinyMCE. My search for a solution has been unsuccessful so far despite extensive googling efforts. (image link: [ ...

"What is the process for developing a Web-component with Vue and typescript that can be used in

Utilizing vue-custom-element, I have successfully created a Web component in Vue and integrated it into Angular. This setup operates seamlessly for Vue+js: import Vue from 'vue' import Calculator from './components/Calculator.vue' impo ...

Transferring data from a child component to a parent component in Angular using @ViewChild requires providing 2 arguments

Currently, I am attempting to transmit data using @Output & EventEmitter and @ViewChild & AfterViewInit from a child component to a parent component. Below is the code from my parent component .html file: <app-child (filterEvent)=" getValu ...

Issue encountered while authenticating client secret from backend for newly created Stripe subscription

There seems to be an issue with confirming the client secret sent from the express backend to the frontend, specifically in a React Native-based mobile application. The clientSecret is being sent in the same manner as described above. On the frontend Rea ...

How to only disable checkboxes that are currently checked in Angular 8

click here to view an image**I would like to know how I can disable only the selected/checked items on a p-listbox in Angular 8. Is it possible to achieve this by adding a specific property or using CSS? Currently, when I try to add the [disabled] proper ...

A specialized HTTP interceptor designed for individual APIs

Hey there, I am currently working with 3 different APIs that require unique auth tokens for authentication. My goal is to set up 3 separate HTTP interceptors, one for each API. While I'm familiar with creating a generic httpInterceptor for the entire ...

What is the best way to create a layout with two images positioned in the center?

Is it possible to align the two pictures to the center of the page horizontally using only HTML and CSS? I've tried using this code but it doesn't seem to work: #product .container { display: flex; justify-content: space-between; flex-w ...

Broaden the current category within the MUI Theme

I am attempting to enhance the current options within MUI's theme palette by adding a couple of properties. Take a look at this example: declare module @material-ui/core/styles/createMuiTheme { interface CustomOptions extends SimplePaletteColorOptio ...

"Encountered a problem while attempting to download the .xlsx file through http.get in an angular application interfacing

Attempting to download a .xlsx file using Angular 7 and web API in C#, encountering the following error: https://i.sstatic.net/7pwDl.png The code snippet from my service.ts is provided below: public exportExcelFile(matchedRows: string, reportInfoId: num ...

Metronome in TypeScript

I am currently working on developing a metronome using Typescript within the Angular 2 framework. Many thanks to @Nitzan-Tomer for assisting me with the foundational concepts, as discussed in this Stack Overflow post: Typescript Loop with Delay. My curren ...

Using Angular 8, remember to not only create a model but also to properly set it

hello Here is a sample of the model I am working with: export interface SiteSetting { postSetting: PostSetting; } export interface PostSetting { showDataRecordAfterSomeDay: number; } I am trying to populate this model in a component and set it ...

Working with Files in TypeScript

New to TypeScript and seeking a command to eliminate the file path and extension. For example, if my file is located at ./data/input/myfile.js, how can I extract only "myfile" without the path and extension? ...

Tips for transferring a value from a component class to a function that is external to the class in angular

Is there a way to pass a variable value from a component class to a function outside the class? I've been struggling to make it work. Whenever I click the button, I receive an error message saying "cannot read property divide of undefined". Here' ...

Shifting the Ion Menu side dynamically based on screen size: A step-by-step guide

Working with Ionic 4, I encountered the need to dynamically change the side property of ion-menu. On larger screens, ion-menu is always visible or static, whereas on smaller screens, it remains hidden until the user clicks on the ion-menu-button. My goal i ...

Is the tooltip display for Typescript types in VSCode reliable? No need for unnecessary type assertions

Exploring the concept of const assertions in TypeScript Looking at the array allDeviceTypes depicted below, VSCode indicates it has a return type of string[] when hovering over the variable name. https://i.sstatic.net/gIYch.png However, upon using a con ...

Different Option for Single-spa

We currently possess a vast enterprise application developed in angularjs. However, we are now faced with the task of transitioning to angular. Consequently, we have dismissed the option of employing the recommended "ngUpgrade" hybrid approach. Hence, we ...

When working with Angular Universal, using d3.select may result in a "reference error: document is not defined" in the server.js file

I'm currently working on an Angular project that uses server-side rendering to generate D3 charts. Each chart is encapsulated within its own component, such as a line-chart component which consists of TypeScript, spec.ts, HTML, and CSS files for rende ...

Nested asynchronous functions in TypeScript

profile.page.ts: username: string; totalScore: number; ... loadUserData() { this.spinnerDialog.show(); this.firebaseServie.loadUserData().then(() => { this.username = this.sessionData.getUser().getUsername(); this.totalSco ...