Angular project language conversion

In my Angular project, I am working with a json file located in src\assets\i18n that contains Swedish translations:

{
  "COMMON": {
    "BUTTON-NO-FILE": "Dokument saknas",
    "BUTTON-EDIT": "Redigera",
    "BUTTON-SAVE": "Spara",
    "BUTTON-CANCEL": "Avbryt",
    "BUTTON-OK": "Ok",
    "BUTTON-CLOSE": "Stäng",
    "ERRORS": {
      "GENERAL-TITLE": "Ett fel har inträffat",
      "401-MSG": "Testing 401 message",
      "499-MSG": "Applikationen svarar inte, försök igen senare.",
      "403-MSG": "Handlingen kan inte utföras, kontrollera din behörighet."",
      "404-MSG"": "Resurserna som du försöker nå finns inte.",
      "400-MSG": "Ett fel har inträffat. Kontakta HSB om felet fortfarande kvarstår."
    }
  }
}

I have added a custom message for error code 401: "Testing 401 message".

Now, there is a logic implemented to map the error messages in the translation json file based on their respective error status:

import {
  HttpEvent,
  HttpInterceptor,
  HttpHandler,
  HttpRequest,
  HttpErrorResponse
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, map, mergeMap } from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { MessageDialogService } from '@hsbweb/hsb-shared-components-module';
import { TranslateService } from '@ngx-translate/core';

@Injectable()
export class HttpErrorInterceptor implements HttpInterceptor {
  constructor(
    private messageDialogService: MessageDialogService,
    private translate: TranslateService) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      return next.handle(request)
          .pipe(
              catchError((error: HttpErrorResponse) => {
                  let errorMessage = '';
                  switch (error.status) {
                    case 499:
                      errorMessage = this.translate.instant('COMMON.ERRORS.499-MSG');
                      break;
                    case 404:
                      errorMessage = this.translate.instant('COMMON.ERRORS.404-MSG');
                      break;
                    case 403:
                      errorMessage = this.translate.instant('COMMON.ERRORS.403-MSG');
                      break;
                    case 400:
                      errorMessage = this.translate.instant('COMMON.ERRORS.400-MSG');
                      break;
                    case 401:
                      errorMessage = this.translate.instant('COMMON.ERRORS.401-MSG');
                      break;
                    default:
                      errorMessage = this.translate.instant('COMMON.ERRORS.400-MSG');
                      break;
                  }
                  this.messageDialogService.error(
                    this.translate.instant('COMMON.ERRORS.GENERAL-TITLE'),
                    errorMessage,
                    this.translate.instant('COMMON.BUTTON- OK'));

                  return throwError(error);
              })
          );
  }
}

Although I have specified the case for the 401-message, it still refers to COMMON.ERRORS.401-MSG instead of the actual value in the translation file.

Do I need to make any changes to the json file after editing it? Even re-compiling the Angular project did not resolve the issue. Being new to Angular, what steps should I take next?

Answer №1

There are a few things to consider in this situation.

  • Instead of passing the string literal 'COMMON.ERRORS.4xx-MSG', it is recommended to remove the quotes.
  • To access items in JSON using Angular, you can utilize the HttpClient to fetch them.

Here is an example of a service that can help you retrieve JSON objects from a file (please note that I have not tested this code yet).

@Injectable({
    providedIn: 'root'
})
export class AppConfigProvider {
    public settings: AppConfig;

    constructor(
        private http: HttpClient
    ) {}

    load(): Promise<any> {
        const jsonFile = `src\assets\i18n.json`;
        return this.http
            .get<AppConfig>(jsonFile)
            .pipe(
                tap(res => {
                    this.settings = res;
                })
            )
            .toPromise();
    }

    public getAppSetting(path: string) {
           return Object.keys(this.settings)
            .filter(setting => setting.includes(path))
            .map(filteredSetting => this.settings[filteredSetting]);
    }
}

You will also need to include the following code for any assets you want your Angular project to load and reference properly.

In your angular.json file under projects.app-name.architect.build.assets[]:

{
 "glob": "*.json",
 "input": "src/assets/config",
 "output": "assets/config"
}

If this seems like too much work, consider replacing the .json file with a constants file in your project. This way, you can simply import those constants as needed instead of creating a complex service like this one.

If you have any questions or need further clarification, feel free to reach out. Thanks!

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

Uploading Multipart Files and JSON Data using Spring Boot

I am looking to create an API using Spring Boot for uploading a multipart file as part of the JSON body, and also to save the image URL in a database. The requests will have the following format: ------WebKitFormBoundarynBsAcX7rJhOGsmfY Content-Dispositio ...

Tips on annotating a SolidJS component with Typescript

I delved into the realm of TypeScript and SolidJS, only to stumble upon this interesting discovery. https://i.sstatic.net/CGvKm.png import { Component } from "solid-js" const Button:Component=({onClick})=>{ return <button onClick={on ...

Data binding not being subscribed to the input decorator

My local variable is not being bound properly when retrieving data from a subscription. In my setup, I have two components and a service. The parent component triggers a method in the service to make an HTTP GET request, which includes a user object that ...

The integration of slot as a prop in rootlayout creates chaos in all routing processes when using Next.js parallel routing

I have a slot called @auth located inside an app folder. Within the @auth folder, there is a login folder with page.jsx containing the following code: import LoginPopup from "@/components/Popups/LoginPopup/LoginPopup"; const Login = () => { ...

What is the best method to delete a value from localStorage using redux-persist?

In my index.js file, I have set up a persist configuration as shown below: import {configureStore, combineReducers} from "@reduxjs/toolkit" import { persistStore, persistReducer, FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER } from 'redu ...

Sweet treats, items, and data interchange format

Can an object be converted to a string, stored in a cookie, retrieved, and then parsed back to its original form when the user logs on again? Here's a concise example of what I'm asking: var myObject = { prop1: "hello", prop2: 42 }; va ...

What are the steps to turn off the blue hyperlinks on iOS devices?

One example of this issue can be observed in time-formatted text like (00:10 - 10:55) and a time select menu displaying (08:00 AM). I have attempted the following solutions, but none of them have resolved the problem: Mobile Safari/iPhone Mail.app HTML ...

Create a Bootstrap modal that includes an object tag to embed a PDF file

I'm currently working on displaying a PDF file within a Bootstrap modal using the "object" HTML tag. However, I am facing an issue where the PDF file is not showing up. To demonstrate this problem, I have created a jsFiddle (http://jsfiddle.net/mV6jJ ...

The removeAllOptions() function is restricted to select, ol, and ul elements. If you try to use it with any other element, an alert will appear during a keyup event on Firefox

The functionality of removeAllOptions() is limited to the following elements: select, ol, and ul. An alert issue has been identified in the Firefox browser where it triggers on keyup events within a text box. ...

Clicking the mouse within three.js

I'm facing an issue with my webpage that features a three.js (webgl) graphic created using a .dae file imported from Blender. My goal is to draw a square or mark wherever the mouse is clicked, but for some reason, the square appears in a different loc ...

Exploring Angular 2/4: Unpacking the Process of Accessing API Data Using Tokens

Hello there, I am trying to retrieve API data with a token using Angular 2/4. Below is the code I have written: import { Component, ViewEncapsulation } from '@angular/core'; import { Http, Response } from '@angular/http'; import &apos ...

The name 'CallSite' is missing from the Error stack trace when working with Node.js and TypeScript

I am facing an issue with the following code: Error.prepareStackTrace = function ( error: Error, stack: Array<CallSite>, ) { return self.parse(fiber, error, stack) } I am attempting to import the CallSite, but it seems like it cannot be found ...

Triggering actionsheet button clicks in Ionic 3

I need assistance with adding buttonClick functionality to actionSheet buttons in ionic 3. When a button is clicked, I want to open a modal (custom alert). Below is the code snippet: openActionSheet() { console.log('opening'); le ...

Unable to associate JSON data using the map method

In the JSON example provided below, I am trying to extract the name of the genres. { "adult": false, "backdrop_path": "/5qxePyMYDisLe8rJiBYX8HKEyv2.jpg", "budget": 178000000, "genres": [ { "id": 12, "name": "Adventure" }, { ...

What is the best way to handle my JavaScript libraries in Grunt - Bower or NPM?

After diving into Grunt, I've come to realize how amazing it can be. However, I have one concern when it comes to managing Javascript libraries. Currently, my workflow involves searching for each library online and placing them in a js/libs folder. Th ...

Navigating back to the top of a webpage within an Angular iframe on Safari desktop

One of my challenges involves an Angular 5 application which is embedded into an Iframe on various sites to create an application form. Whenever a user clicks 'Next' to move to the next section of the form, I require the page to scroll back to th ...

execute task to optimize CSS encoding in the build process

Creating a static project with yeoman -webapp I've implemented a UTF checkmark in my .scss files: [type="checkbox"]:checked + label:after { content: '✔'; position: absolute; top: 3px; left: 0px; font-size: 22px; color:$color-pr ...

Confirm that the array contains exactly 2 elements

Is there a way to confirm that an array contains exactly two specific values, for example: ['foo', 'bar'] After trying different approaches, the closest solution I found looks like this: Yup.array() .of(Yup.mixed().oneOf(['foo&a ...

Extract the entire div including all its elements and then transmit it using the PHP mail function

Currently, I am developing a feature that allows users to send an email. The email should include only one div from the page which contains elements added using the jQuery drag and clone function. I am unsure how to copy the entire div along with its child ...

Is there a way to automatically update and utilize the access token for a socket connection?

After successfully logging in, I am able to obtain an access token and establish a socket connection. However, I have encountered an issue where the access token does not automatically update itself when the user logs out and back in again. As a result, my ...