Utilizing Angular 14 and Typescript to fetch JSON data through the URL property in an HTML

Is there a way to specify a local path to a JSON file in HTML, similar to how the src attribute works for an HTML img tag?

Imagine something like this:

<my-component data-source="localPath">

Here, localPath would point to a local JSON file containing the data to be used by my-component. This would allow me to use the same component multiple times in my HTML, but with each instance reading from a different JSON file.

I have successfully implemented this for a single instance within my-component.component.ts:

import myData from 'localPath';
let content = myData.data as MyInterface;

This solution is based on a previous question I posed regarding Angular 12 and JSON file reading. However, the drawback here is that all instances of my-component are restricted to using the same JSON file at localPath.

I am considering creating a service to handle file loading, similar to how you would retrieve data from an external URL or API. But I wonder if there's a simpler approach since I am only dealing with local files, not external sources.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class MyService {

  constructor(public http: HttpClient) { }

  getData(url: string): Observable<Record<string, any>> {
    return this.http.get(url)
      .pipe(map((res) => {
        return res;
      }))
  }
}

The above code snippet is inspired by a blog post and includes a fix mentioned in my earlier inquiry.

An ideal scenario would involve usage like this:

<div>
    <my-component data-source="./localPath/data1.json" />
    <my-component data-source="./localPath/data2.json" />
</div>

In this setup, data1.json and data2.json represent two distinct files serving as data sources for separate instances.

Answer №1

I am currently attempting to access a file on my local machine

This claim of it being "local" can be misleading as all data and code actually originates from the http protocol. For example, if you have one js file (along with some css and index.html) and wish to include a json file, you would either need to add that json content directly into the js file or make an additional http request to load it.

Here are three methods for loading a json file: https://stackblitz.com/edit/angular-read-local-json-file?file=src%2Fapp%2Fapp.component.html

The second and third methods involve using http requests to retrieve the json content.

In the first method, which involves Typescript imports (your preferred approach), the json file is actually included in one of the loaded files with no separate json file residing on the server.

If you opt for this method of reading a json file, you will need to incorporate it into your application source code by importing all necessary files in one place, such as within a service:

import myData1 from 'localPath1';
import myData2 from 'localPath2';
...

class JsonHolderService {
   store = {};
   constructor() {
      this.store['localPath1'] = myData1;
      this.store['localPath2'] = myData2;
      ...
   }
}

You can then access this data in your components.

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

Display the concealed mat-option once all other options have been filtered out

My current task involves dynamically creating multiple <mat-select> elements based on the number of "tag types" retrieved from the backend. These <mat-select> elements are then filled with tag data. Users have the ability to add new "tag types, ...

Using Angular in conjunction with Azure Durable Functions to implement a retry mechanism for HTTP responses

In my Angular 10 application, I am attempting to integrate Azure Functions. The key is to simplify the Azure function protocol by using a single Observable. Executing an Azure function requires the following steps: Initiate a POST request to the Azure fu ...

Issue with memory leakage detected during compilation of Angular 12 application

My coworker and I are currently in the process of optimizing our Angular 12 application for our enterprise. The Issue: One major challenge we have encountered while developing our application is the continuous increase in memory usage each time the angul ...

Troubleshooting Problems with Google Maps and Javascript/JSON in Internet Explorer

Currently, I am utilizing the Google Maps API to construct a map that displays store locations in close proximity to a user-specified location. Everything is functioning properly, however, I am encountering an error in Internet Explorer that I would like t ...

Differentiating Service Class and Typescript Class in Angular 6

I am looking for a detailed explanation of service classes in Angular. From my perspective, both service classes and typescript classes serve the same purpose. So, what sets them apart from each other? ...

Nested Elements in Java JSON with Jackson

I have a JSON string that contains nested values. It looks something like this: "[{"listed_count":1720,"status":{"retweet_count":78}}]" I am interested in extracting the value of retweet_count. Currently, I am using Jackson to work with this data. The ...

Transforming JSON Object to a Different Object using Mule ESB

My current process is as follows: <?xml version="1.0" encoding="UTF-8"?> <mule xmlns:json="http://www.mulesoft.org/schema/mule/json" xmlns:db="http://www.mulesoft.org/schema/mule/db" xmlns:tracking="http://www.mulesoft.org/schema/mule/ee/trackin ...

Convert JSON into a class with the 'paste special' feature is not available in Visual Studio 2019, even though all web

One useful feature is the ability to easily extract JSON and generate a class from it. In previous versions of VS, Paste Special was a handy tool, but I can't seem to find it in Visual Studio 2019. After checking out this forum thread, it seems addin ...

Is there a way to ensure that the await subscribe block finishes before moving on to the next line of code?

My goal is to utilize the Google Maps API for retrieving coordinates based on an address. In my understanding, using await with the subscribe line should ensure that the code block completes before moving on to the subsequent lines. async getCoordinates ...

Troubleshooting Problem with Uploading Several Photos to Firebase Storage

I need assistance with uploading multiple photos to Firebase Storage. Despite my efforts, it seems that the original upload keeps getting overwritten and the folder with the venueID property is not being created. Can someone provide some guidance on this i ...

Obtain pictures from MongoDB for a website using Angular6

I'm currently in the process of developing my website and I want to showcase an image from my database on the header. Each customer is assigned a unique logo based on their ID, but I'm unsure how to use Angular to display it. Below is my code s ...

Create a line chart with multiple lines using data retrieved from either JSON or MySQL

At the outset, I must confess that I am not a programmer, although I am slowly getting the hang of it. My interest lies in utilizing graphs for Horticultural purposes. Currently, I have a database that receives data from sensors hourly, and my query retrie ...

Seems like the ng-show events inside are not being triggered, almost like an invisible image

I am encountering an issue where no JavaScript events are triggering inside an ng-show div in my code. You can access my code through the following link on Plnkr: http://plnkr.co/edit/kGqk8x?p=preview Upon loading data from JSON, I set ng-show to true. Ho ...

Is there a way to deserialize JSON into an empty struct within a function without losing its type information?

Can someone help me with a question regarding JSON unmarshalling? I am facing an issue where the type is lost after unmarshalling the data. Here's an example of what I'm experiencing: package main import ( "encoding/json" " ...

Can you identify the specific error type that occurs in the onError function of react-query's MutationCache when using Typescript

Can someone help me with identifying the type of error in react-query MutationCache onError function when using Typescript? I also need guidance on how to override the type so that I can access and use the fullMessage from the data. const queryClient = new ...

A guide to accessing an ngModel element within a reusable component

I have a specific ngModel component inside a reusable component that is not part of a form. I need to access it in order to make some changes, but when I try to do so using the code below, it returns undefined during OnInit. Can you advise me on how to pro ...

Access the array values by their respective keys in an object that is returned from a custom JavaScript file utilizing the Node.js file system

I recently came across a config file with a unique format, as shown below: define([], function () { return { productItems: { item1: ['Apple', 'Ball', 'Car'], item2: [&apo ...

An issue was encountered while serializing `.dehydratedState.queries[0].state.data.config.adapter` in Next JS, which was returned from `getServerSide

Struggling to fetch data using react-query in the Next JS getServerSideProps function, I encountered a perplexing error: Error: Error serializing `.dehydratedState.queries[0].state.data.config.adapter` returned from `getServerSideProps` in "/auth/goog ...

A TypeScript object with user-defined keys

I have a question about utilizing TypeScript records with a custom Type as keys. Essentially, I have a specific type (a limited set of strings) that I want to use as keys for my record. My goal is to start with an empty initialization of this record. type ...

loading images from a server in a dynamic manner within a list view on an Android application

I'm relatively new to android development and I've created a database with different user profiles, each containing an image URL. Now, I want to fetch the image URLs from the database for a specific user and display them in an Android ListView. ...