Retrieving JSON data with Typescript

https://i.sstatic.net/i5vFM.jpg

I recently received some data from a request, expecting to return a JSON object that I can utilize in HTML. However, upon running

console.log(this.data);

I noticed that there are 20 elements in the articles array, but it returns as undefined or null when I execute

console.log(this.data.__zone_symbol__value);

I would greatly appreciate any assistance in resolving this issue. :)

Edit made in response to comment:


ngOnInit() {
    this.url = 'https://newsapi.org/v2/top-headlines?' +
        'country=us&' +
        'apiKey=c6aecd1cd1de49edaca2544076713c45';
   this.Newsdata = this.FetchHeadlines(this.url);

   console.log(this.Newsdata);
   console.log(this.Newsdata.__zone_symbol__value);

}

get(url: string): Promise<any> {
    return new Promise((resolve, reject) => {
        var req = new XMLHttpRequest();
        req.open('GET', url);

        req.onload = () => {
            if (req.status === 200) {
                resolve(req.response);
            } else {
                reject(Error(req.statusText));
            }
        };

        req.onerror = () => {
            reject(Error('Network Error'));
        };

        req.send();
    });
}

FetchHeadlines(url: string): Promise<any> {
    console.log("Entered FetchHeadlines");

    return this.get(url).then(JSON.parse).catch(error => {
        console.log('getJSON failed for', url, error);
        throw error;
    });
}

Answer №1

By using the single line method JSON.parse(), everything functions smoothly.

Method One

private getData() {
        let url = "https://newsapi.org/v2/top-headlines?country=us&apiKey=c6aecd1cd1de49edaca2544076713c45";
        console.log("Fetching Headlines");

        this.fetchHeadlines(url).then((response)=>{
            let Data=JSON.parse(response);
            console.log("Data",Data);
            console.log("Articles",Data.articles);

        })      
    }
    fetchHeadlines(url: string): Promise<any> {
        console.log("Fetching Headlines");

        return this.get(url).then().catch(error => {
            console.log('Error fetching JSON for', url, error);
            throw error;
        });
    }

    get(url: string): Promise<any> {
        return new Promise((resolve, reject) => {
            var req = new XMLHttpRequest();
            req.open('GET', url);

            req.onload = () => {
                if (req.status === 200) {
                    resolve(req.response);
                } else {
                    reject(Error(req.statusText));
                }
            };

            req.onerror = () => {
                reject(Error('Network Error'));
            };

            req.send();
        });
    }

Tested and worked perfectly. Screenshot, https://i.sstatic.net/xINzd.png

Method Two:-

private getData(){
        let url="https://newsapi.org/v2/top-headlines?country=us&apiKey=c6aecd1cd1de49edaca2544076713c45";
            console.log("Entered FetchHeadlines");

            this.http.get(url).subscribe((response)=>{
                console.log("Response1",response);
                console.log("Response2",response.json());   //you can assign value to a variable here         
            })
    }

Screenshot,

https://i.sstatic.net/1id6t.png

I trust that the first method resolves your issue.

Thank you, Muthukumar

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

Issue: The specified selector "app-redirect" does not correspond to any elements. I am currently in the process of transitioning to MSAL v2 and need to retrieve a refresh token

[Seeking Console Error Resolution import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { SharedModule } from './shared/shared.module' import { AppRoutingModule } from ...

A simple guide on how to surround every incorrect input index in mapped inputs with red borders

I am incorporating a modal that corresponds each element of the object newCompanies to a specific row: {newCompanies.map((company, index) => { return ( <div> <div className="side- ...

Error: The function call does not match any of the overloads. 'VueRouter' is not recognized

I'm new to TypeScript and currently trying to implement vue-router in my project. Encountering the following errors: Error TS2769: No overload matches this call in source\app\main.ts(3,3). Overload 1 of 3, '(options?: ThisTypedCompon ...

Looking to eliminate a significant gap of white space

I have been scouring the internet for hours, gathering a lot of information, but unfortunately, I haven't found exactly what I'm looking for. I have implemented this specific code in my WordPress website Additionally, I have integrated infinite ...

Display a loading alert using SweetAlert2 that requires no user interaction

Currently, my code looks like this: swal({ title: 'Loading cars from data base', showLoaderOnConfirm: true, preConfirm: () => { return this.carsSvc.getCars().then((cars: ICar[]) => { this.setData(cars); ...

Utilize Odoo CRM API and Zapier integration to generate new leads and opportunities

I'm in the process of setting up Zapier to send a webhook request to Odoo in order to generate a new lead/opportunity when data is retrieved from Facebook Ads. Instead of relying on Zapier's pre-built automation, I prefer to use Webhooks for a m ...

Generate dropdown options from JSON data

I've been on a quest to solve what seems like a basic issue, but my search has come up empty...any assistance would be greatly appreciated. My goal is to construct a dropdown box using a JSON object fetched from a PHP script. The PHP file (versions.p ...

Creating a component that consists of nested subcomponents and implementing useImperativeHandle

I am attempting to create a Component with SubComponents. The Component is utilizing the useImperativeHandle hook, so forwardRef is necessary. Here is my current code snippet: const MyComponent = Object.assign(forwardRef(function(props, ref){ useImper ...

What is the best way to shift <p> slightly to the left using css?

I've created an HTML file structured like this. <html> <head> </head> <body> <div class="final_time"> <p class="final_time_text">some text here</p> </div> </b ...

Next JS Event Listener Failing to Detect Scroll Events

Currently, I am attempting to change the state and display a shadow in the navigation bar when the user scrolls, but for some reason it is not detecting the event. I am working with nextJS 13 and tailwind css. const [shadow, setShadow] = useState(false) ...

As the width decreases in animation, the content gradually disappears until it reaches zero

My issue involves red and black divs; when I hover over the parent element, the red div should appear by expanding to its full width. However, a problem arises when the width is set to 0px as the content still shows. Can someone provide assistance on how t ...

What is the new Bootstrap equivalent for btn-group-justify?

Could someone help me align the 3 radio options in this HTML code to make them appear justified? I have already tried using d-flex and btn-group-justify without success. If anyone could provide a sample using only Bootstrap 4.1+, it would be greatly appre ...

How can Angular be configured to automatically save file modifications?

Currently, I am utilizing VSCode and running ng serve -o to showcase my changes immediately. My goal is to enable automatic saving after modifying each file, enhancing my development workflow by viewing the updates instantaneously in the browser. ...

Using Retrofit's GsonConverterFactory to convert JSON objects that are invalid or false

I am currently dealing with a server that returns JSON data. One of the elements within this data can be either an object or false if it does not exist. I understand that this is not the best way to structure server responses, but unfortunately, I have to ...

Locate the checkbox label using CSS

Is there a way to replace the standard checkboxes with font-awesome icons without modifying the generated HTML or using jQuery? EDIT: The code includes JavaScript that prevents me from making changes. Also, note that the label text class can be -1 or -2 a ...

PHP - Issue with submitting form data using $_POST from within a Div text container

Having some trouble with the submission of the "about_me_container" div in my form using $_POST. I know that divs are not typically used with $_POST, so I tried changing the div to input type="text" and textarea but it still won't work. I also attempt ...

Exploring the World of JSON Nested Arrays with Unknown Titles and Organizing Them for Storage

Apologies if this question has already been addressed elsewhere, but I couldn't find it. I have a JSON object with dynamic keys: { "main": [ { "Example1": [ { "Example1_Var02": "5", ...

Methods for Expanding a Div within an Oversized Row, Despite Height Constraints

I have a situation where I need to adjust the height of a cell in a table. One of the cells contains a larger element that causes the row to expand vertically. I also have another cell with a div element set to 100% of the cell's height. However, I wa ...

What is the best way to incorporate unique styles into a component element directly from the parent HTML that houses it?

I have created a unique component called app-details-banner-component.html: <div class="container"> <div class="row"> <div class="col-7"> <h1 class="project-title">Details</h1&g ...

Why is it that injecting javascript within innerHTML seems to work in this case?

According to the discussion on this thread, it is generally believed that injecting javascript in innerHTML is not supposed to function as expected. However, there are instances where this unconventional method seems to work: <BR> Below is an examp ...