Encountering 'propertyof undefined' error while attempting to import a local JSON file in Angular/Ionic

I am looking to display data in an HTML file that is sourced from a local JSON file.

The structure of my JSON file is as follows:

{
"ACCESSIBILITY_EXPANDED": "Expanded",
      "ACCESSIBILITY_BACK": "Back",
      "ACCESSIBILITY_COLLAPSED": "Collapsed",
      "ACCESSIBILITY_PHONE_NUMBER": "Call us at",
      "ACCESSIBILITY_EMAIL": "Email us at",
      "ACCESSIBILITY_ADDRESS": "Visit us at",
      "ACCESSIBILITY_FAX": "Send us a FAX at",
}

To achieve this, I made modifications to my tsconfig.json file:

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types",
      "src/typings.d.ts"
    ],
    "lib": [
      "es2018",
      "dom"
    ],
    "allowSyntheticDefaultImports": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
  }
}

I also created a typings.d.ts file within my src folder with the following content:

declare module "*.json" {
    const value: any;
    export default value;
}

In my component's .ts file, I added the following line:

import en from '../../assets/i18n/en.json';

However, when I tried to use the data in my HTML file like this

 <span class="bolded"> {{ en.ACCESSIBILITY_BACK }}</span> 

I encountered an error stating "Cannot read property ACCESSIBILITY_BACK of undefined" even though the object is logged properly when I console.log(en) in ngOnInit(). Any suggestions on how to resolve this issue? Thank you.

Answer №1

{{ en }} represents a template property that must be assigned to a component property:

@Component({
  template: '...<span class="bolded"> {{ en.ACCESSIBILITY_BACK }}</span>...'
})
export class A11yComponent {
  // assigns `en` from json to a component property `en`
  en = en;
}

Alternatively, you can utilize interpolation in the template string or concatenation, although this may not work with AoT compilation.

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

Having multiple template bindings on a single element is not possible. Please utilize only one attribute with the prefix "*" for </mat-header-cell>

I encountered the following error: ERROR in Can't have multiple template bindings on one element. Use only one attribute prefixed with * (" <mat-header-cell> <mat-cell *matCellDef="let order" class="{{orderColum ...

Using jQuery and Ajax to send the content of a single textbox to a controller for processing

I am currently developing a timesheet application and I want to incorporate an autosave feature. Here is an example of the form structure: <form id="timesheet" action="save_timesheet.html" method="POST"> <input type="text" id="day1taskid2" /> ...

What is the best way to generate a dynamic table row in Angular Material?

Could someone assist me with implementing expandable rows in my HTML table using Angular Material, similar to the example in this image: https://i.sstatic.net/QJtFX.png The concept is that when the content in a cell is too long, clicking on that cell will ...

The result after calling JSON.parse(...) was not accurate

The following method is used in the controller: @RequestMapping(value = "channelIntentionDetails.html", method = RequestMethod.POST) public @ResponseBody Report getChannelIntentionDetails(@RequestBody SearchParameters searchParameters) { LOGGER.in ...

Removing header from Json using Gson

I utilized Gson to create a Json as shown below val gson = new Gson val jsonString = gson.toJson(mydata). println(jsonString) output: {"mydata":{"date":["2008-06-04T22:47:36Z"], "pdf:PDFVersion":["1.6"], "pdf:docinfo:title":[" PDF Test Page"], ...

jQuery Ajax error: unexpected token!

I've been attempting to retrieve a JSON file using the following code: $.ajax('/file.json', { contentType: 'application/json', dataType: 'jsonp', success: function (data) { console.log(data); }, ...

Leverage the power of the async pipe with ngFor on an Observable containing Observables within Angular

I have a variable defined in this way: myVar: Observable<Observable<MyObject>[]>. I am utilizing an Angular4 feature to iterate using the async pipe *ngFor="let obsMyObject of (myVar | async)" Currently, I have an Observable of MyObject, but ...

Exchange information between two components and a service in a continuous loop

My Angular application retrieves a JSON object from an API, and I want to accomplish this through a service. The app has a search component that queries the service, which in turn fetches the data. View example diagram Next, the second component needs t ...

Managing custom types in hashtable serialization and deserialization using ASP.NET

I'm trying to send a hashtable through a post request, but in order to do that I need to convert the hashtable to json format. Currently, I am utilizing Newtonsoft JSON.NET for this task. Hashtable ht = new Hashtable(); User u = new User(); u.name = ...

A guide on retrieving an array of objects from a JSON file

Trying to access the array results from the API at , but encountering an error message stating "cannot fetch value of undefined." import React, { Component } from 'react'; class App extends Component { constructor() { s ...

Error TS2322: This type cannot be assigned to type 'never' in Angular

Trying to incorporate the websocket (sockjs and stomp) into my Angular project for a chat messaging feature, I encountered an issue in my service.ts file. Specifically, when I defined the addMessage method like so: public messages = []; addMessage(messa ...

What is the best way to showcase a random index of an array in typescript?

Imagine a scenario where you have created a method that captures an array and selects a random position from it. The task at hand is to display one or more of these random positions on the screen. While you have successfully used the *ngFor directive to di ...

Tips on modifying JSON information from various collections of key-value pairs

What is the best way to manipulate JSON data by changing values from multiple key-value pairs in Java? ...

Definition of type instantiation in TypeScript

When utilizing the mynew function with a specified array of classes, I am encountering an error related to defining unknown. How can I modify this definition in order to eliminate the error? export interface Type<T> extends Function { new (...arg ...

What causes an ObjectUnsubscribedError to be triggered when removing and then re-adding a child component in Angular?

Within a parent component, there is a list: items: SomeType; The values of this list are obtained from a service: this.someService.items$.subscribe(items => { this.items = items; }); At some point, the list is updated with new criteria: this.some ...

Encountering a build error in ng serve right after running npm install

After deleting the node_modules directory and rebuilding it with npm install, I encountered an error in my angular2 app when using cmd ng serve. Error: 'common-tags' module not found at Function.Module._resolveFilename (module.js:337:15) ...

Seeking a guide on how to effectively utilize Angular 6 for consuming REST API and performing CRUD operations

I am a beginner with Angular and I am currently using Version 6, specifically the CLI tool. My main focus right now is learning how to make REST API calls. I have searched for tutorials on this topic but unfortunately, none of them have been successful fo ...

What is the best approach: Developing a class or a service to handle multiple interfaces?

My current project involves creating multiple interfaces, and I would like to keep them separate for clarity. Would it be wise to do this in a service or a class? Additionally, is it possible to utilize dependency injection for classes? Thank you for your ...

Is it possible to change the default behavior in Dapper where retrieving nvarchar(max) values is trimmed to 4000 characters?

Within my SQL Server data table, there is a column that stores a JSON string representing a serialized .NET object. The length of this JSON string typically exceeds 4000 characters. For data retrieval, I have a basic stored procedure set up: @StageID ...

Output certain values in a Python dataframe based on the lambda function applied

I am currently working on a piece of code that involves reading a json file and using a lambda function to remove certain values. Here is the code snippet: import pandas as pd data = pd.read_json('filename.json',dtype='int64') data = da ...