There was an error parsing the data from the specified URL (http://localhost:8000/src/client/assets/data.json

Hey there, I'm a newcomer to Angular and I'm having trouble reading a JSON array from a file. Every time I try, it gives me a "failed to parse" error. Can someone please provide some guidance?

Here is my folder structure:

src

--assets
    ---app
      -----opportunities
            ------opportunities.component.ts
--data.json

The data in my data.json file looks like this:

[  
    {
     "Account name": "155874744",
     "Oppty owner": "Sony Europe Ltd.",
     "Product/s": "June 10, 2015",
     "Domestic/Mow": "55434992111033",
     "ASAP solution status": "Aasd",
     "Price scenario status": "$253.00"         
    },
    {
     "Account name": "155874744",
     "Oppty owner": "Sony Europe Ltd.",
     "Product/s": "June 10, 2015",
     "Domestic/Mow": "55434992111033",
     "ASAP solution status": "sds",
     "Price scenario status": "$253.00"        
    }     
]

Below is the code in opportunities.component.ts:

 constructor(private httpservice:HttpClient){}
  public  opptyData:any[];
    ngOnInit()
    {                 
      this.httpservice.get('src/client/assetsdata.json').subscribe(data=>{
                this.opptyData = data as string[];
                console.log(this.opptyData[1]);
            },
            (err:HttpErrorResponse)=>{
                console.log(err.message);
            }
            );
    }

I'm really struggling to figure out what the issue is. Any help would be greatly appreciated!

Answer №1

For the desired URL, you can use the following code snippet:

this.httpservice.get('./data.json').subscribe(data=>{
     this.opptyData = data as string[];
     console.log(this.opptyData[1]);
}

Answer №2

If you're looking to structure your front-end using dummy JSON, a recommended option is to utilize this website

Simply paste your JSON, select your options, and click on Generate my HTTP response. This will provide you with a service link that can be temporarily used in your code. Alternatively, you can also explore the method suggested by Sajeetharan.

Best of luck!

Answer №3

Save information in the assets directory:

located at src/assets/data.json

Directory Layout:

src
   -assets
      -data.json

access the data like this: // (assets/data.json)

constructor(private httpservice:HttpClient){}
  public opptyData:any[];
    ngOnInit()
    {

            this.httpservice.get('assets/data.json').subscribe(data=>{
                    this.opptyData = data as string[];
                    console.log(this.opptyData[1]);

            },
            (err:HttpErrorResponse)=>{
                console.log(err.message);
            }

            );

    }

OR -------------------------------------------------------------------------------------------------------------------------------

Directory Layout:

src
   -assets
     -client
       -data.json

access the data like this: // (assets/client/data.json)

constructor(private httpservice:HttpClient){}
  public opptyData:any[];
    ngOnInit()
    {

            this.httpservice.get('assets/client/data.json').subscribe(data=>{
                    this.opptyData = data as string[];
                    console.log(this.opptyData[1]);

            },
            (err:HttpErrorResponse)=>{
                console.log(err.message);
            }

            );

    }

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 trouble passing parameters to Next JS when using the Courtain.js library

Greetings everyone, I am in the process of developing a website and I have encountered an issue with inserting a distorted image with animation on the homepage. After using a library called Courtain.js, a developer managed to make it work and provided me ...

Creating dynamic select boxes in Django Admin using jQuery

In my Contract class, the contract_mod field is designed to extend a contract from a previous one and should only display contracts related to the selected person. The Contract class returns the person field, but since I have no experience with AJAX/jQuery ...

When working with AngularJS, you can enhance your application by implementing a global AJAX error handler if one has

Is there a way to set a global AJAX handler that will only be called if an error handler is not already defined for a specific AJAX call? Some of my AJAX calls need to execute certain logic if an error occurs (such as re-enabling a button), while others s ...

The ngFor directive in Angular2 consistently collapses the identical <tr> element

Greetings, I am a newcomer to the world of web development. Recently, I used the *ngFor directive in Angular to generate multiple rows with collapsible details. However, when I click on a row, it always collapses the same div, instead of the corresponding ...

I am receiving a success message from webpack indicating that the compilation was successful, but I am encountering a blank page in the

My app.js looks like this: import Home from "./pages/home/Home"; import Login from "./pages/login/Login"; import Profile from "./pages/profile/Profile"; import Register from "./pages/register/Register"; import { Brow ...

Best practices for managing storage objects that contain references to other storage objects?

Imagine a scenario involving a billiards application. In this case, there is a requirement for a model called Match, which refers to multiple instances of the Game object. Each Game object contains scoring data related to a specific game. Both the Match an ...

Struggling to eliminate nesting in a JSON array using PHP

Looking for assistance with flattening a JSON array that contains nested elements under the "DEMARCHE" key. The current code only returns a single output array, but there are multiple arrays within my JSON file. Any help would be greatly appreciated. _ Tha ...

The click() function in jQuery executing only once inside a "for" loop

This is an example of my HTML code: <!DOCTYPE html> <head> <title>Chemist</title> <link href="stylesheet.css" rel="stylesheet"> </head> <body> <h2 id="money"></h2> <table border="1px ...

The 'fullDocument' property is not present in the 'ChangeStreamDropDocument' type

Upon cloning an express TypeScript project, I encountered a Typescript error within a Mongo related function as mentioned in the title. Property 'fullDocument' does not exist on type 'ChangeStreamDocument<IUser>'. Property &apos ...

"Select2 dropdown search bar vanishing act: The hunt for results comes up empty

Currently, I am dealing with a scenario involving two modals, each containing a select2 search dropdown. An issue has arisen where selecting modal one filters the dropdown data effectively. However, upon selecting modal two, although the data is filtered i ...

Error: Unable to bind 'datasets' as it is not recognized as a valid property of 'base-chart' in ng2-charts

Current Versions: Cordova: 6.3.1, Gulp CLI: 1.2.2, Ionic framework: 2.0.0-rc.0, Ionic CLI Version: 2.1.0 In my Ionic2 application, I have integrated the ng2-charts library. When importing, be sure to use import {ChartsModule} from "ng2-charts/components/ ...

Display the results from the API in a div using Vue.js

Currently working on implementing dynamic buttons to fetch data from an API call. Struggling with pushing the data array to the template and div. Here is my VueJS setup: var example = new Vue({ el: '#example', data: function () { ...

What steps should I take to create code that can generate a JWT token for user authentication and authorization?

I'm struggling to get this working. I have a dilemma with two files: permissionCtrl.js and tokenCtrl.js. My tech stack includes nJWT, Node.js/Express.js, Sequelize & Postgres. The permission file contains a function called hasPermission that is linke ...

Even after trying to hide the legend in a Radar Chart using the configuration option `legend: {display: false}` in chart.js, the legend

Having trouble removing legend from Radar Chart in chart.js even when using legend: {display : false}. The code is being utilized and then displayed with HTML/JS. Here is the provided code snippet: var options5 = { type: 'radar', data: { ...

What is the alternative method for reading an HTML text file in JavaScript without utilizing the input type file?

Within the assets folder, there is a text file containing HTML that needs to be displayed within a specific component's div. Is it possible to retrieve the contents of this file and assign them to a string variable during the ngOnInit lifecycle hook ...

Defining variables within a jQuery function

Within my initialization function (init), I have defined some variables and an animation that utilizes those variables. The challenge arises when I want to use the same animation/variables in my clickSlide function. http://jsfiddle.net/lollero/4WfZa/ (Un ...

Events related to key press timing in HTML 5 canvas

Currently, I am developing a game similar to Stick Hero for Android using HTML5. I am working on the code that will capture the time of key press (specifically the right arrow key with ASCII 39) in JavaScript and expand a stick accordingly. <!doctype h ...

Building a web proxy with node.js and express

I'm currently in the process of designing a personalized web proxy using JavaScript to allow users to surf the internet through a designated website, similar to this . One challenge I encountered is transferring the response from a URL back to the us ...

The iPad screen displays the image in a rotated position while it remains

Recently, I developed a mini test website that enables users to upload pictures and immediately see them without navigating back to the server. It seemed quite simple at first. $('input').on('change', function () { var file = this. ...

What is the best way to convert exponential values to decimals when parsing JSON data?

var value = '{"total":2.47E-7}' var result = JSON.parse(value); Looking to convert an exponential value into decimal using JavaScript - any suggestions? ...