Using Angular to import a JSON file stored locally

I am facing an issue with importing a .json file in my Angular project. The file is located outside the project structure as shown below:

| common
    | configuration.json
| angular-app
    | src
        | app
            | my-component
                | my-component.component.ts
    | angular.json

Within the my-component.component.ts file, I have attempted to import configuration.json using

import configuration from '../../../../common.configuration.json'
. However, Angular keeps throwing the following error:

ERROR in src/app/record/record.component.ts(4,23): error TS2732: Cannot find module '../../../../common/configuration.json'. Consider using '--resolveJsonModule' to import module with '.json' extension

Upon trying ng serve --resolveJsonModule, I encountered this error message:

Unknown option: '--resolveJsonModule'

Unfortunately, moving the configuration.json file is not an option as the common directory is shared with other projects.

How can I successfully import a local json file in an Angular project?

Answer №1

If you're working with typescript 2.9+ (Angular 6.1+), importing JSON modules is now possible for them to be compiled into your application. However, older versions do not have this feature which may be causing the issue you are facing.

To enable this functionality, ensure that the following three compiler options are set in your tsconfig.json file:

{
  ...
  "compilerOptions": {
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true
    ...
  }
}

Once these options are enabled, you can easily import JSON modules within any TypeScript file:

import jsonContents from '../../contents.json';

Answer №2

Experiment with making an http request:

this.http.get(`yourpath/..../common/configuration.json`).subscribe((response: any) => {
   console.log(response)
});

Answer №3

I'm a bit unsure of your question, but it seems like you're looking to utilize the configuration values within your component, correct?

As per a helpful guide, one way to address this issue entails creating a type definition file named json-typings.d.ts in your main app directory with the subsequent code snippet:

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

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

Error: Unable to connect to 'ngbTypeahead' as it is not recognized as a valid attribute of 'input' in the template

Having trouble with ngbTypeahead. The console is displaying the following error message: Error: Template parse errors: Can't bind to 'ngbTypeahead' since it isn't a known property of 'input'. (" <inpu ...

Is there a way to attach a Blob/File array to formData in typescript?

If I didn't have an ARRAY of files, this method would work perfectly. However, it needs to be in the form of an Array. let file1 = new File([""], "filename"); let file2 = new File([""], "filename"); let fi ...

typescript is reporting that the variable has not been defined

interface User { id: number; name?: string; nickname?: string; } interface Info { id: number; city?: string; } type SuperUser = User & Info; let su: SuperUser; su.id = 1; console.log(su); I experimented with intersection types ...

Tips for simulating or monitoring an external function without an object using Typescript 2 and Jasmine 2 within an Angular 4 application

In order to verify if a function called haveBeenCalledWith() includes the necessary parameters, I am seeking to validate the correctness of my call without actually executing the real methods. I have experimented with multiple solutions sourced from vario ...

Empty initial value for first item in array using React hooks

My goal is to store an array that I retrieve from an API in a useState hook, but the first entry in my array always ends up empty. The initial array looks like this: (3) ["", "5ea5d29230778c1cd47e02dd", "5ea5d2f430778c1cd47e02de"] The actual data I recei ...

Choosing between Angular's Observable and Subject as a DataSourceWhen it comes

I am currently working on an Angular 7 application that utilizes Mat Tables to retrieve data from an API. I have implemented dynamic pagination values, where the pageSizeOptions value changes based on a dropdown selection when loading the grid. By default, ...

Obtain the Key with the Greatest Value from a JSON Object

I'm currently working with data fetched from an API response in an attempt to identify the pitch with the highest speed. Below is a snippet from the API response. { page: 1, total_pages: 4, listings: [ { name: "Zack Greinke", pitc ...

Tips for conducting tests on ngrx/effects using Jasmine and Karma with Angular 5 and ngrx 5

Here is the file that I need to test. My current focus is on some effects service while working with Angular5 (^5.2.0) and ngrx5 (^5.2.0). I have been struggling to properly implement the code below for testing purposes. Any tips or suggestions would be ...

Error encountered in Angular 6 Application running on .Net Core within a Docker Container due to Npm issue

After developing an Angular 6 .Net Core 2.1 application that should be operational in a Linux Docker container, I encountered an issue when attempting to run it using docker compose. Strangely, the application works perfectly fine when launched with npm st ...

When a function is included in an object, it transforms into something other than a function

In my model, it looks like this: export default class UserObject { name: string; id: string; validateInsert() { } } If I interact with the model in this way: const modelUser: UserModel = new UserModel(); modelUser.ID = 1; modelUser ...

Injecting pipes into directives in Angular: A guide

I've developed a custom directive that formats input values based on the provided pipe parameter (@Input) in Angular reactive forms. For this functionality, I had to import the necessary pipes (currently just one) and implement a switch mechanism to ...

Exploring the capabilities of argon2-browser in a cutting-edge setup with vite

After spending several hours attempting to implement the argon2-browser library in a Vue app with Vite, I have been encountering a persistent error. Despite following the documentation closely, I keep receiving the following message: This require call is ...

The functionality of React setState seems to be malfunctioning when activated

Having encountered an unusual issue with react's setState() method. Currently, I am utilizing Azure DevOps extensions components and have a panel with an onClick event that is intended to change the state of IsUserAddedOrUpdated and trigger the addOr ...

Fetching and displaying JSON objects in a Rails view

I have implemented a search functionality on my Rails application. The Search controller is responsible for fetching spaces based on a query in the model, and then returning them as JSON. In order to retrieve this data, I am utilizing $.getJSON within a vi ...

"Experiencing sluggish performance with VSCode while using TypeScript and Styled Components

My experience with vscode's type-checking is frustratingly slow, especially when I am using styled components. I have tried searching for a solution multiple times, but have only come across similar issues on GitHub. I attempted to read and understa ...

What is the best way to transfer image files into a specific folder?

I am currently in the process of developing a ReactJS web application. My goal is to upload images to a specific folder and then store the file name in the database for future use. Everything seems to be working smoothly up to this point, but I am facing ...

retrieve the JSON object corresponding to the specific category

Here is an example of a JSON: [ { "id":1, "name": "BMW E46 PANDEM", "price": 130000, "currency":"USD", "color":"white", "category":"car" }, { "id":2, "name": "Yamaha", "price": 2000, "currency":"USD", "c ...

Guide to aligning a component in the middle of the screen - Angular

As I delve into my project using Angular, I find myself unsure about the best approach to rendering a component within the main component. Check out the repository: https://github.com/jrsbaum/crud-angular See the demo here: Login credentials: Email: [e ...

Using Observables for Polling in Angular 8

Greetings, I am in the process of upgrading my project from Angular 5 to Angular 8. Below is the code snippet I used for polling: Observable.interval(this.intervalTime).timeout(600000) .takeWhile(() => this.alive) .subs ...

How should a React Testing Library wrapper be properly typed in a TypeScript environment?

There's this code snippet from Kent C. Dodd's library that I find extremely helpful import * as React from 'react' import {render as rtlRender} from '@testing-library/react' import {ThemeProvider} from 'components/theme& ...