How can I retrieve the content of a JSON file and store it in an attribute of my

Just starting out with Angular 2 (first day!)

I'm working on a class that has 3 fields: id and name which are passed to the constructor, and a third field called data which should hold the content of a JSON file.

export class Hero {
    id: string;
    name: string;
    data: Object;

    constructor(id: string, name: string) {
        this.id = id;
        this.name = name;

        //retrieve JSON and assign it to this.data
        var request = new XMLHttpRequest();
        request.onload = function(){
            var result = JSON.parse(this.responseText);
            this.data = result;
        };

        //get the json file based on the object's id
        request.open("get", id+".json", true);
        request.send();

    }
}

Then I create an instance of the object like this

new Hero("hero1", "Hero 1");

The issue is that the instruction this.data = result; doesn't work because this refers to the request object, not the class itself.

Also, I'm not sure if this is the correct approach (or even how to properly fetch the JSON file). I'm still pretty confused in my Angular 2 journey. Thanks!

Answer №1

Consider utilizing arrow functions

    Instead of using a traditional function, switch to an arrow function like so:
        request.onload = () => {
            var result = JSON.parse(this.responseText);
            this.data = result;
        };

Answer №2

Here's another approach you can take:

class Superhero {
    superpower: string;
    alias: string;
    details: Object;

    constructor(superpower: string, alias: string) {
        this.superpower = superpower;
        this.alias = alias;

        let xhr = new XMLHttpRequest();
        xhr.onload = this.onDataReceived.bind(this, xhr);

        xhr.open("get", alias + ".json", true);
        xhr.send();
    }

    private onDataReceived(xhr: XMLHttpRequest): void {
        let response = JSON.parse(xhr.responseText);
        this.details = JSON.parse(response);
    }
}

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

Incorporating a new data series into your candlestick chart with Highstock

I've encountered an issue with adding a data series to my candlestick chart in Highstock using Highcharts. Here's the script I'm using: $.ajax({ url : 'indicator', type : 'GET', data ...

What is the best way to add an item to an array with distinct properties?

I am currently working on creating an array with different properties for each day of the week. Here is what I have so far: const [fullData, setFullData] = useState([{index:-1,exercise:''}]) My goal is to allow users to choose exercises for a sp ...

What is the best way to change an asterisk symbol into 000 within a currency input

In my ASP.NET application, I have a currency text box. I have the following script: <script type="text/javascript> function Comma(Num) { //function to add commas to textboxes Num += ''; Num = Num.replace(',', ...

combine several arrays next to each other based on a specified key

I have a collection of three sets, each containing three elements: Set1 = [[apple, 2, 4], [banana, 5, 5], [cherry, 4, 1]] Set2 = [[banana, 1, 7], [cherry, 3, 8], [date, 5, 4]] Set3 = [[apple, 5, 2], [banana, 0, 9], ...

Typescript: Declaring object properties with interfaces

Looking for a solution to create the childTitle property in fooDetail interface by combining two properties from fooParent interface. export interface fooParent { appId: string, appName: string } export interface fooDetail { childTitle: fooParent. ...

While trying to parse JSON in Swift, I keep encountering a typeMismatch error

After calling my API and receiving the expected response based on my model setup, I encountered an unexpected error. typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", ...

Having difficulty utilizing RubaXa/angular-legacy-sortablejs to transfer items from one list to another

Could anyone explain why I am having trouble moving items between two lists on this plunk? I've successfully implemented shared lists using the RubaXa Sortable library and plain Javascript, but I'm facing challenges with Angular and the RubaXa/a ...

"Utilizing d3 to parse and track variables within JSON data

To calculate the number of occurrences of s1, s2, and s0 in JSON data and use this information to plot a multiline chart with date (path of date is as follows reviews_details>>variable vf of JSON) on the X-axis versus the number of reviews (s1/s0/s2 ...

How can I assign the output of a function to a variable within a class in Angular?

Is there a way for the Army class to automatically update its CP property with the sum of CP values from all Detachments in the Detachment class? In the Army class, the CP property should reflect the total CP value from all Detachments and be accessible t ...

Acquire information from JSON object and array sources

Looking for a solution to extract LAT & LON from multiple points in JSON data. Here is an example of Java code that extracts list keys: public void loadPositions(JSONObject result){ try { JSONObject jObject = result.getJSONObject("points"); ...

Avoiding label overlap with JavaScript

I've mapped a textured image onto a sphere and added labels to it, but some of the labels are overlapping. I'm looking for ways to separate them without altering the "lon" and "lat" values. Could someone please advise me on how to achieve this or ...

Field Invalid in Asana

I am trying to send the following JSON data to asana's "tasks" endpoint using a POST request. { "data": { "options": { "fields": [ "name", "notes" ] }, "workspace": & ...

Two vertical containers dynamically adjusting their height together

I am facing a challenge with two containers that need to share the height of their parent element. The second container is added dynamically when needed, and both containers may contain a lot of content, requiring scroll capabilities. While I have a solut ...

What is the most effective way to prevent actions while waiting for ajax in each specific method?

Within my JS component, I have various methods that handle events like click events and trigger ajax requests. To prevent the scenario where multiple clicks on the same button result in several ajax requests being fired off simultaneously, I typically use ...

Producing flawless soundtracks using the createSound(); function

Struggling to generate a sound using createSound(); and here's the code snippet: function preload(){ s = createAudio('sound.wav') } function setup(){ createCanvas(400, 400); s.play(); } function draw(){ background(0, 0, 0); } Encou ...

problems with hovering over radio buttons in Internet Explorer 9

Encountering a curious issue in IE9: When hovering over my top level wrapper div, the first radio button seems to be triggered as though it's being hovered over. This means that even if the last radio input is selected, clicking anywhere within the wr ...

How can I define Record values in Typescript based on their specific keys?

I am working on creating a custom data structure that allows me to store values with string keys within the union string | number | boolean: type FilterKey = string; type FilterValue = string | number | boolean; type Filters<K extends FilterKey, T exten ...

Ending the Overlay

I am using an overlay: <div id="overlayer" class="overlayer"> <div id="board" class="board"></div> </div> Here are the CSS properties I have applied to it: #overlayer { position:fixed; display:none; top:0; left:0; width:100%; hei ...

Centering the NavBar

I am encountering a small issue with the justify-content-sm-center property. I am trying to center this <a class="navbar-brand" href="#">Navbar</a>, but when I attempt to center it, the toggler icon is also centered along wi ...

I am unable to deliver an email to the mailbox

Whenever I try to send an email, I encounter an issue. In order to complete the registration process, a confirmation mail needs to be sent. The error message that I receive is: Callback must be a function at maybeCallback const fs = require(& ...