Get a list of objects from a JSON array of objects using HTTP requests in Angular 5 with Typescript

I am trying to extract an array of objects from another JSON array, which is received through an HTTP request in Angular 5. My goal is to display the values in the console. I have successfully made the HTTP request and subscribed to the service.

When using *ngFor in the template, everything works fine. However, when I try to access it directly in the Typescript file, the value appears as undefined in the console.

This is how my JSON data looks:

{"data":[
   {
   userId: 1,
   id: 1,
   title: 'Loreum ispum',
   body: 'dummy text' 
   },
   {
   userId: 1,
   id: 1,
   title: 'Loreum ispum',
   body: 'dummy text' 
   },
   {
   userId: 1,
   id: 1,
   title: 'Loreum ispum',
   body: 'dummy text' 
   }]
}

While I can access the data using ngFor in the HTML file and retrieve the values, accessing it in Typescript with console.log(this.obj[data]) results in undefined being displayed.

I need to create a new array that only includes the id and title fields in Angular 5. Any assistance on this matter would be greatly appreciated.

Here is my Service page:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpResponse } from'@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
const httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable()
export class ConfigService {
private URL: string = 'some URL';
constructor(private http:HttpClient) {}
getData(): Observable<any>  {
return this.http.get(this.URL+ '/getdata', {responseType: 'json'});
}
}

And this is my component:

import { Component, OnInit, Input } from '@angular/core';
import { ConfigService } from '../services/config.service';
import { FormControl } from '@angular/forms';
import { SelectionModel } from '@angular/cdk/collections';
import { FlatTreeControl } from '@angular/cdk/tree';
import { Observable, BehaviorSubject } from 'rxjs';
@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class childComponent implements OnInit {
allData: any = [];
  getALLData() {
    this.config.getData().subscribe(
      data => { this.allData= data['data']},
      err => console.error(err),
      () => console.log('done loading data')
    );
  }

  ngOnInit() {
    this.getALLData();
    console.log(this.allData);   // In this case, the console shows 'undefined'
  }
}

If you have any suggestions or solutions, please let me know. Thank you!

Answer №1

The HTTP service responds with a response object containing the requested data.

const request = this.http.get('...');

// Subscribing triggers the HTTP request, and you can subscribe again on the same variable for another request
request.subscribe((resp)=>{ 
    // This will display the response object.
    console.log(resp);
});

It is recommended to use either take or first to ensure the HTTP request is fully executed.

request.first().subscribe((resp)=>{ 
        // Avoiding memory leaks now
});

Error handling is essential.

request
   .first()
   .catch((err,o)=>console.error(err))
   .subscribe((resp)=>{
       // Executed only if successful
   });

If the HTTP request succeeds, you can map the response to retrieve the server's actual data.

request
   .first()
   .catch((err,o)=>console.error(err))
   .map((resp)=>resp.data)
   .subscribe((data)=>{
       // JSON data from the server will be displayed
       console.log(data);
   });

This is how I would implement the HTTP service function.

 getFoods() {
     return this.http
                .get('....')
                .first()
                .catch((err,o)=>console.error('An error occurred'))
                .map((resp)=>resp.data);
 }  

In your component, make sure to log the response data only after the observable has completed.

 this.data = null;
 console.log('data is null', this.data);
 this.server.getFoods().subscribe((data)=>{
      this.data = data;
      console.log('data is now set', this.data);
 });
 console.log('data is still null', this.data);

This addresses the query by loading data lazily once the HTTP request concludes.

Answer №2

It was incredibly beneficial in learning how to fetch JSON array data from an API into Angular.

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 one element in Angular 2 while concealing the rest

Problem: I am facing an issue with my accordion containing 4 elements. When I click on the first element, it displays not only its content but also the content of the other 3 elements. Expected Solution: I want to be able to click on a specific element ...

I am experiencing an issue where the mat-header-cell components are not appearing after navigating

After initially loading the page, mat-header-cell displays fine. However, upon navigating to a second page, refreshing it in the browser, and then returning to the original page, the mat-header-cell is no longer visible. It only reappears after manually re ...

The monorepo contains TypeScript files with a .js extension, causing confusion for IDEs that are unable to recognize TypeScript code within them

After cloning the React monorepo from GitHub and opening it as a new project in WebStorm IDE, I encountered an issue. It turns out that all the .js files in this repository are actually written in TypeScript, causing confusion for the IDE. For instance: / ...

To utilize RxJS 6+, the 'Observable' type needs to include a 'Symbol.iterator' function that generates an iterator

I encountered an issue when attempting to filter an array of values from an observable: The error message I received was: 'Type 'Observable' must have a 'Symbol.iterator' method that returns an iterator' Here is the code s ...

Attempting to create an animated carousel slider

I've been working on creating a carousel animation that displays 3 images, slides them to the left, and brings in new ones. I'm feeling a bit stuck and could use some assistance. Check out my work so far on this fiddle link: http://jsfiddle.net/ ...

Implementing conditional properties in Typescript based on the value of another property

Is it possible to make a property required in a type based on the presence of another property? Here's an example: type Parent = { children?: Child[]; childrenIdSequence: string[]; // This property should only be required when `children` is prov ...

Importing TweenLite in Typescript is a breeze

After downloading the GSAP package via npm, I am keen on importing the TweenLite class to my TypeScript app. While importing all of GSAP can be achieved by using require('gsap'); and it functions correctly, this method does not work in TypeScript ...

Expanding the capabilities of button properties in MUI

My goal is to customize the MUI5 components by extending their ButtonProps interface and utilizing the component prop. Following the guidelines provided in the documentation, I implemented the solution as shown in the code snippet below: import Button, ...

Deciphering an encrypted password with Crypto-js displays an incorrect outcome

I have implemented a register and login feature in my auth.ts file, which I am currently testing using Postman. The library I am utilizing is crypto-js, which I have used in Node.js before, but this is my first time using TypeScript. I have installed @type ...

When setting up Angular material, be prepared for a thorough audit uncovering nearly 600 vulnerabilities

I want to utilize the drag and drop features provided by the @angular/material module, however, when I install it using angular cli, multiple vulnerabilities are flagged during the audit process. While the program functions as expected, attempting to run n ...

Calculate the cumulative total by ID within a specific date range using MongoDB

I am currently working with a json file that contains purchase records for 4 different customers on various dates. My task is to use MongoDB/nosql to determine which customers have made a minimum total of 8 new purchases over a span of 3 consecutive days. ...

Has anyone successfully incorporated Load more pagination in an Android app using a JSON parser?

Attempting to add a load more pagination feature in android for my listview using JSON Parser. Came across a tutorial for XML parser here. Any suggestions on how to achieve this with JSON? ...

Assigning labels to array components based on the longest dimension

I'm looking to create a matrix that grows with dimension names. Here's the code I'm using: completeMatrix = matrix(c(1:20), nrow=10, ncol=2) for (i in 1:3){ newMatrix <- matrix(c(1:20), nrow=10, ncol=2) completeMatrix <- abind(co ...

Display information in an HTML table using JQuery AJAX and JSON data

As a new member and beginner learner, I have encountered some issues while trying to execute a certain task. Despite looking at similar questions, I couldn't find a solution that worked for me. What I am attempting to do is query my database to retrie ...

Struggling to implement a click event followed by DOM manipulation

Every time I start the game, 4 characters are randomly generated in my starting function, and then they are displayed in the Character Div. The next step is to click on one of the four characters (vader, stormtrooper, luke, or yoda). Once a character is cl ...

Integration of conditional array output into a different array

Here is a code snippet that creates an email campaign and sends it to specific segments in Mailchimp: $data = array("recipients" => array( "list_id" => "$listId", "segment_opts" => array( ...

Issue NG8002: Unable to connect with "status" as it is not recognized as a valid attribute of "a"

I am encountering an issue with tslint in my Angular 9 project. Every time I save the file, the material component changes to lowercase ( matInput => matinput). There seems to be a problem with the casing. Here is the app component code snippet: import ...

Error message "The file 'EXTERN.h' cannot be located" appears during Perl module installation

Whenever I attempt to install Perl modules such as JSON::XS or YAML::XS, I encounter a recurring issue: XS.xs:1:10: fatal error: 'EXTERN.h' file not found I am currently using a MacBook with an updated xCode and all other relevant software is ...

Different methods to prompt TypeScript to deduce the type

Consider the following code snippet: function Foo(num: number) { switch (num) { case 0: return { type: "Quz", str: 'string', } as const; case 1: return { type: "Bar", 1: 'value' } as const; default: thr ...

Transforming Tab Separated Text Files into JSON Format

Is there a more direct way to convert a 1.9GB tab delimited file in the form of an xlsx file to JSON without having to convert it to CSV first? Any insights or suggestions are greatly appreciated. Thank you! :) ...