How to Load a JSON File in Angular 13 Using the HTTP Get Method

I have been attempting to retrieve JSON data from a local file in the assets folder. Despite searching for solutions on Google, I have not been able to find one that works as desired.

I created a service with the following code:

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

@Injectable({
  providedIn: 'root'
})

export class JSONService {
    public JSONArr: any;

    constructor(private http: HttpClient ) { }

    initJSON(path: string = "") { 
        this.JSONArr = this.getJSONArr(path);
        
        console.log("@ Service");
        console.log(path);
        console.log(this.JSONArr);
        // return this.JSONArr;
    }

    async getJSONArr( path: string = ""): Observable<any> {
        return this.http.get(path).subscribe(data => { 
            this.JSONArr = data;
            console.log(data);
        }
    }

    
}

The path is provided from the app.component.ts The JSON looks like this

{
        "title": "Testtitle",
        "content": "Test Message"
}

My issue is: The console.log within the getJSONArr function correctly displays the JSON data, but the console.log within the initJSON function returns undefined

Can anyone provide assistance?

Answer №1

It seems like you're approaching it the wrong way because an HTTP request is asynchronous. Therefore, if you try to console.log this.JSONArr, it will display as undefined.

In your service, the only thing you can do is:

async getJSONArr(path: string = ""): Observable<any> {
   return this.http.get(path);
}

Furthermore, in your component, you just need to use the subscribe method to retrieve data from the JSON file.

Component.ts

this.yourService.getJSONArr(yourPath).subscribe((jsonData) => console.log(jsonData));

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

Challenges with using forRoot and other function calls in AOT compilation

Upon compiling my app, I am faced with the error message: "Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol Declaran ...

When an iteration occurs within a for loop and a value changes, remember to incorporate a line break or equivalent element using jQuery

I am currently working on implementing a hierarchy system for users stored in a database table. At the moment, only top-level users with a hierarchy of 1 are displayed. When clicked, I use AJAX to retrieve and display all related users below them. These ...

What steps can I take to troubleshoot and fix the issue of a Duplicate identifier 'DateType' error during the React/Typescript building process

Utilizing the MUI library, I have also installed the @mui/x-date-pickers library. In order for my datepicker component to function properly, I need to install the @date-io/date-fns/ library as well. However, upon running yarn build, I encountered the fol ...

Transform the array into an object containing corresponding key-value pairs

In my dataset, I have an array containing various values: [ { "factor": { "data": "f1", "val": [ "val1" ] } }, { "factor": { "data": "f2", "val": [ "val2" ] ...

Leverage Python to extract data from JSON across various dictionaries

I am looking to extract the values of keywords from the provided JSON file. For example: output = ['abc,'cde'] The structure of the JSON file is as follows: d = [{ "response": {"docs": [ {"keywords": [{"value": "abc"}]}, ...

What is the method to reference a class instance using a local variable?

class D { y = 1; }; let E = D; function F(arg2: E){ arg2.y }; ERROR in [at-loader] ./src/syntax/colletion-range.ts:10:18 TS2749: 'E' refers to a value, but is being used as a type here. ...

Is there a method other than reset() to eliminate userId from segment analytics when using typescript?

I am utilizing the @segment/analytics-next library to track segment events. The following code shows how I initialize a segment analytics and set a userId: import { AnalyticsBrowser } from '@segment/analytics-next'; let segmentAnalytics = new Ana ...

What is the best way to retrieve JSON or JSONP data cross-origin from the visistat.com API using Ajax?

Currently, I am utilizing the below API call in jQuery to fetch data. I have added ?callback=? at the end to bypass the cross-origin domain issue; without it, I encounter a cross-domain error. When using Chrome, it notified me with, "Resource interpreted ...

What is the purpose of importing the HttpClientModule in app.module.ts when it has already been imported in a different module specifically for its use?

Currently, I am working with 2 modules named AppModule and BookModule. In BookModule, a component is injected with a service that utilizes HttpClient, so I had to import HttpClientModule in it. However, the application still requires importing HttpClientMo ...

Personalize the as_json output in Ruby

Currently, I am working on building REST APIs in Ruby and utilizing @object.as_json() for the JSON response format. However, I have encountered a roadblock in customizing the data transfer within the as_json method. I have outlined my specific requirement ...

Enclose the type definition for a function from a third-party library

I prefer to utilize Typescript for ensuring immutability in my code. Unfortunately, many libraries do not type their exported function parameters as Readonly or DeepReadonly, even if they are not meant to be mutated. This commonly causes issues because a ...

Encountered a 'node:internal/modules/cjs/loader:1146' error while setting up a React application

Encountering these console errors node:internal/modules/cjs/loader:1146 throw err; ^ Error: Module '../../package.json' not found Require stack: - C:\Users\adity\AppData\Roaming\npm\node_modules\npm\li ...

Executing a function once the Angular Component's DOM has been updated, just like how ngAfterViewInit works

I have a unique feature in my component that creates multiple directives based on user input. The simplified example below demonstrates how the component receives configuration data through an Input(), processes it using a service called MyService to gener ...

Converting Java data to JSON using a Jquery script

Does anyone know of a jQuery method that can convert a Java data object into JSON format? I am currently utilizing the HTTPResponse object to deliver my object to my ajax, but it is returning a String object. Note: JSON.parse is not an option and I am una ...

Navigating to an external URL from Angular 6 using POST method

I have been working on integrating a payment gateway into my Angular app. I came across this JavaScript snippet provided by the payment partner for integration, and after adding ngNoForm, I was able to make it work seamlessly with Angular. You can check ou ...

Ways to extract data from a double array JSON using AngularJS

I am dealing with a JSON file that contains 2 arrays holding some data which I need to retrieve for my AngularJS website. My aim is to extract a single object from these 2 arrays. JSON data [ { "DailyForecasts": [ { "key": "32.48,44.4 ...

Creating a nested list in AngularJS using the ng-repeat directive

My experience with AngularJS is limited, but I am tasked with modifying a web app that requires nesting lists inside each other: <ul class="first-level"> <li ng-repeat="item in list">{{item.parentNo1}} <ul class="level-2"> ...

In search of an effective method for converting circular objects into string format

After some thorough research, I've encountered a plethora of broken links and explanations that were quite complex for me to follow. I am inquiring about this for a gaming application scenario, where an owner possesses an item that is also held by th ...

How can we use a base-class to deserialize Json into a generic entity in C#?

I am looking for a way to easily convert JSON objects to entity classes without having to write redundant code multiple times. That's why I created a base class for my entities and now I want to deserialize them without knowing which specific derived- ...

Angular 5 with Typescript encountered a failure in webpack due to the absence of the property "data" on the Response

I am encountering an issue during webpack compilation. It compiles successfully if I remove .data, but then the page crashes with calls from template->component (which in turn calls a service). Here is the error I am facing: ERROR in src/app/compone ...