Displaying the complete response on Angular is possible, but JSON only shows the full response

I'm currently working on a project, and my main concern is: how do I access the response from the first array when all arrays have identical attribute names like body? similar to this: console.log and screen

Everything works fine on a simple JSON server.

I need to list the batches in this array to display the results on this screen:

I've tried almost everything, but no luck;

  • Using the index search function;
  • Filtering the array using the filter function;
  • Mapping the array using the map function.

But perhaps I am approaching this incorrectly? here's the service that needs to be fetched:

import { Injectable, OnInit } from '@angular/core';
import {HttpClient, HttpParams} from '@angular/common/http';
import { Observable } from 'rxjs';
    
@Injectable({
      providedIn: 'root'
})
export class LotesService implements OnInit{

  readonly apiURL = `http://localhost:3000`;
  readonly lotesURL = 'item';
  readonly registrosURL = 'registros';

  readonly termId = '?id=';
  readonly mode = mode.CONTINUABLE;
  readonly size = 2000;
  readonly elements = 2000;
  readonly continuable = 'ODEwODE3ODQwMDMwMTIyMDQ3';
  readonly selector = Selector;

  constructor(private httpClient: HttpClient) {
  }
  
  //Function to Fetch Batches on Lotes API - Listar Lotes
  getLotes(situacao: situacao.ATIVO){
    let params = new HttpParams()
    .set('situacao', situacao);
    return this.httpClient.get<any[]>(`${this.apiURL}/${this.lotesURL}/`,{params: params});
  }

export enum situacao {
  ATIVO = "ATIVO",
  INATIVO = "INATIVO",
  REMOVIDO = "REMOVIDO",
}

and here's the batch component:

import { Lote, situacao} from 'src/app/services/lotes.service';
import { Component, OnInit, ChangeDetectorRef} from '@angular/core';
import { Injectable } from '@angular/core';
import { environment } from './../../../environments/environment';
import { HeaderService } from 'src/app/services/header-service.service';
import { LotesService } from 'src/app/services/lotes.service';
import { PageEvent } from '@angular/material/paginator';

@Component({
  selector: 'app-lotes',
  templateUrl: './lotes.component.html',
  styleUrls: ['./lotes.component.css'],
})

//status 200 always
@Injectable({
  providedIn: 'root'
})

export class LotesComponent implements OnInit {
  MostrarColunas: string[] = ['id', 'dataProcessamento', 'quantidadeClientes', "quantidadeParcelas", "situacao"];
  lotes: Lote[] = [];
  dataSource = this.lotes;

  public pageslice = this.lotes.slice(0, 5);
  
  pageSize = 3;
  pageIndex = 0;
  pageSizeOptions = [3, 6, 9];
  showFirstLastButtons = true;
  handlePageEvent(event: PageEvent) {
    const startIndex = event.pageIndex * event.pageSize;
    let endIndex = startIndex + event.pageSize;
    if (endIndex > this.lotes.length) {
      endIndex = this.lotes.length;
    }
    this.pageslice = this.lotes.slice(startIndex, endIndex);
    this.pageSize = event.pageSize;
    this.pageIndex = event.pageIndex;
  }

  constructor(private loteService: LotesService,
    private headerService: HeaderService,
    private changeDetectorRef: ChangeDetectorRef) {
      this.lotes = [];
  }

  ngOnInit() {
    this.headerService.setTitle('Lotes');
    this.BuscaLotes();
    this.changeDetectorRef.detectChanges();
  }
  
  BuscaLotes() {
    this.loteService.getLotes(situacion.ATIVO).subscribe(
      data => {
        this.lotes = data;
        console.log(this.lotes);
      },
      error => console.log(error)
    );
  }

}

my object:

export class Lote {
  constructor(
    public id: any,
    public dataProcessamento: Date | "dd/MM/yyyy",
    public quantidadeClientes: number,
    public quantidadeParcelas: number,
    public situacao: situacao
    ) {}
}

My query is: How can I extract the Json data to only display the body attribute?

json data:

"item": [
        {
            "name": "lotes - Listar lotes",
            "request": {
                "method": "GET",
                "header": [
                    {
                        "key": "Authorization",
                        "value": "Basic dGl2ZWE6UzRjTDdmUDl0RW1nYkNnTmxJRnBsekpBSlV5UGpVQjZkcUVKV2tnNDVYMGkw"
                    },
                    {
                        "key": "Content-Type",
                        "name": "Content-Type",
                        "value": "application/json",
                        "type": "text"
                    }
                ],
                "url": {
                    "raw": "https://{{HOST}}/api/assessorias/lotes",
                    "protocol": "https",
                    ...

maybe I'm overlooking something?

thank you in advance, and go easy on me! it's my first post here

Answer №1

If you were only receiving one item, you could use the pluck method.

import { pluck } from 'rxjs/operators';

searchItems() {
    this.itemService.getItems()
    .pipe(
      pluck('info')
    ).subscribe(
      data => {
        this.items = data;
        console.log(this.items);
      },
      error => console.log(error)
    );
  }

However, since you are dealing with an array, you need to map over the array:

searchItems() {
    this.itemService.getItems()
    .subscribe(
      data => {
        this.items = data.map((item) => item.info);
        console.log(this.items);
      },
      error => console.log(error)
    );
  }

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

Implementing a Dropdown Menu Within a React Form

I am currently working on setting up a reservation system for rooms. I want to include 2-4 different room types and incorporate a dropdown menu instead of manual input. I am using the guidance provided here. I attempted to use <Form.Select...>, but i ...

Eliminate the bottom border from the MUI Input component

Is there a way to get rid of the bottom-line borders on these input fields? I attempted using CSS but couldn't find a solution for this component -> <Input type={"text} /> ? https://i.sstatic.net/4QpWym.png ...

Transitioning from AngularJS version 1.5.0 to 1.5.8

My bower.json file contains various dependencies, including AngularJS at version 1.5.0. I am looking to update AngularJS to version 1.5.8 without causing issues for my team members. I attempted to use bower install angular#1.5.8 --save, but this resulted ...

Grails: Javascript function for updating the image source is unresponsive

I have a situation where I need to change the src of an img based on a certain condition. The condition is returning true as expected, as confirmed by an alert() that I added previously. However, the function responsible for changing the src of the img and ...

How to eliminate the yellow box in Three.JS when working with EdgesGeometry, LineSegments, and BoxHelper

Three.js Version: 82 I recently came across an interesting example on the official Three.js website: In this example, I noticed the presence of yellow boxes surrounding the 3D models. Previously, in version 79, I used THREE.EdgesHelper to outline the 3D ...

Triumph awaits before the final response is delivered

Being new to web development, I am currently working on my first web application using purely node.js. In the registration process, form data is sent from the client-side to the server and then stored in the database. Upon a successful response, the client ...

Transforming JArray into an Object with specific attributes

I am faced with the challenge of converting a JArray into an Object using Attributes because I cannot modify the existing call in a decoupled class: var message = JsonConvert.DeserializeObject(e.Message, messageType) The JSON data to be converted is as f ...

Combining Arrays Equally and Alternating using JavaScript and Google Apps Script

I am attempting to evenly and alternately merge multiple arrays in JavaScript/Google Apps Script. I have about 5 or 6 arrays that I need to merge. I have tried two different methods, but unfortunately, neither has worked for me. I don't have much expe ...

Leverage - Utilize the object sent through the render method in an external JavaScript file

In my index.js file, I am sending an object from Express using the render function like this: app.get("/chat", function(req, res){ res.render("chat", {user: req.user}); }); The object can be utilized in my chat.ejs file: <% if(!user){ %> <l ...

Error: Unable to access the 'prototype' property of an undefined object (inherits_browser.js)

After updating our app to a newer version of create-react-app, we started encountering the following error: https://i.sstatic.net/ILdsl.png This error seems to be related to inherits_browser.js, which is likely from an npm module that we are unable to id ...

Calculate the total amount from the selected items on the list, depending on the clicked ('active') element

My main objective is to achieve the following: Before any clicks || After the user selects the desired item After conducting some research, I successfully implemented this using vue.js https://jsfiddle.net/Hanstopz/Lcnxtg51/10/ However, I encountered ...

Using Typescript to collapse the Bootstrap navbar through programming

I've managed to make Bootstrap's navbar collapse successfully using the data-toggle and data-target attributes on each li element. If you're interested, here is a SO answer that explains a way to achieve this without modifying every single ...

Service call delay not displayed on screen

I have a function that I execute in my component's ngOnInit lifecycle hook. This function calls a service to fetch data and populate an array. Once that array is filled, I then call another service method using the data from the first array to populat ...

Tips for achieving expansion of solely the clicked item and not the whole row

I am trying to create a card that contains a cocktail recipe. The card initially displays just the title, and when you click on a button, it should expand to show the full menu and description. The issue I'm facing is that when I click on one element, ...

What is the most effective method for retrieving Key-Value Pairs from a disorganized String?

Avoiding hard-coded rules specific to certain patterns is crucial. I am currently working on a project similar to AWS Textract (link here). I have successfully extracted data from files, albeit in an unstructured manner. Now, my goal is to find the best w ...

What is the best way to code a JavaScript function that changes the labels on a mat-slider when using a range

As a newcomer, I am currently working with a mat-slider and trying to modify the label based on the range selected. However, I'm unsure how to write JavaScript code for different labels. Can anyone provide me with assistance? Here is the mat-slider th ...

Submit a list of checkboxes selected to Google Sheets separated by commas

Is there a way to modify the script I'm using to enter data from an HTML form into a Google Sheet so that my checkbox fields will be entered as a list, separated by commas? If all boxes were checked in the example form below, I would like the cell fo ...

Creating a Signature Request in HTML format with DocuSign

I have successfully implemented the functionality for PDF documents and now I am looking to experiment with an HTML document. My approach involves POSTing a JSON object that includes the base64 encoded bytes of the document. While most examples online util ...

Securing my JSON Server Data with angularJS: Best Practices

Ensuring Security for JSON Server Data in angularJS I have concerns about protecting the URL of my JSON Server Data within the Controller. How can I safeguard it from any potential vulnerabilities on the client side? The URL for my JSON Server Data can b ...

The object's key values were unexpectedly empty despite containing data

There's an issue with my object - it initially gets key values, but then suddenly loses them all. All the key values become empty and a message appears in the console for the object: "this value was evaluated upon first expanding. it may have ch ...