Angular 15 is unfortunately not compatible with my current data consumption capabilities

I'm currently facing an issue with Angular 15 where I am trying to access the "content" element within a JSON data. However, when attempting to retrieve the variable content, I am unable to view the elements it contains.


import { Component, OnInit } from '@angular/core';
import { Contacto } from '../contacto';
import { ContactoService } from '../contacto.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialog } from '@angular/material/dialog';
import { ContactoDetalheComponent } from './contacto-detalhe.component';
import { PaginaContacto } from './PaginaContacto';


@Component({
  selector: 'app-contacto',
  templateUrl: './contacto.component.html',
  styleUrls: ['./contacto.component.css']
})
export class ContactoComponent implements OnInit{

  formulario: FormGroup = new FormGroup('')
  contacto: Contacto
  contactos: Contacto[] = new Array
  paginaContactos: PaginaContacto[] = []
  paginaContacto: PaginaContacto = new PaginaContacto
  mensagem: string = ''
  errors: string[] = []
  colunas: string[]= ['foto', 'id', 'nome', 'email', 'favorito']
  pageSizeOptions: number[] = [5, 10, 15, 20]

  constructor(
    private contactoService: ContactoService, 
    private formBuilder: FormBuilder,
    private dialog: MatDialog){
    
    this.paginaContacto.totalElements = 0
    this.paginaContacto.pageNumber = 0
    this.paginaContacto.pageSize = 5

    this.contacto = new Contacto('','')
  }

  ngOnInit(): void {
  ... more code ...
  }
... more code ...

  listarContactos(page: number, size: number){
    this.contactoService
    .listar(page, size)
    .subscribe({
      next: response =>{
        
        this.contactos = response.content
   
      console.log("imprimindo o erro.")
      console.log(response)

    }, 
      error: errorResponse =>{
        console.log('Erro ao obter os contactos', errorResponse)
      }
  })
  }

... more code ...

}



import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Contacto } from './contacto';
import { Observable } from 'rxjs';
import { environment } from 'src/environments/environment.development';
import { PaginaContacto } from './contacto/PaginaContacto';
@Injectable({
  providedIn: 'root'
})
export class ContactoService {

 apiUrl: string = environment.API
  constructor(private httpCliente: HttpClient) { }

... more code ..

  listar(page: number, size: number): Observable<PaginaContacto[]>{
    const params = new HttpParams()
          .set('page', page)
          .set('size', size)
          
    return this.httpCliente.get<PaginaContacto[]>(
      `${this.apiUrl}?${params}`,  
      {responseType:'json'}
    );
  }

}

import { Contacto } from "../contacto"

export class PaginaContacto{
    content: Contacto[] = new Array()
    pageNumber: number = 0
    pageSize: number = 0 
    totalPages: number = 0
    totalElements: number = 0
}

I have attempted the following:

this.contactos = response.content
this.contactos = response[:content]
this.contactos = response["content"]
this.contactos = response[0].content
this.contactos = response.map(contact => {
   return contact.content
})

Unfortunately, none of these methods seem to work as expected.

This is the response displayed in the browser console:


{
    "content": [
        {
            "id": 8,
            "nome": "Vicente Simão",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f0869993959e8495b0979d91999cde939f9d">[email protected]</a>",
            "favorito": true,
            "foto": null
        },
        {
            "id": 15,
            "nome": "Novo Adiconado",
            "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a6c8c9d0c9e6c1cbc7cfca88c5c9cb">[email protected]</a>",
            "favorito": false,
            "foto": null
        }
    ],
    "pageable": {
        "sort": {
            "sorted": true,
            "unsorted": false,
            "empty": false
        },
        "pageNumber": 5,
        "pageSize": 2,
        "offset": 10,
        "unpaged": false,
        "paged": true
    },
    "totalPages": 7,
    "totalElements": 14,
    "last": false,
    "first": false,
    "sort": {
        "sorted": true,
        "unsorted": false,
        "empty": false
    },
    "numberOfElements": 2,
    "size": 2,
    "number": 5,
    "empty": false
}


Answer №1

The object you are receiving in JSON is not an array.

When using the listar method in the ContactoService, it is recommended to return an Observable of type any or PaginaContacto instead of PaginaContacto[].

Please note that if you choose to return as Observable<PaginaContacto>, ensure that the properties of your class match with the properties from the JSON response.

listar(page: number, size: number): Observable<any>{
  const params = new HttpParams()
        .set('page', page)
        .set('size', size)
          
  return this.httpCliente.get<any>(
    `${this.apiUrl}?${params}`,  
    {responseType:'json'}
  );
}

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 parsing JSON in Android with Retrofit 2 and Gson?

Within my Android application, I am utilizing Retrofit 2 along with GSON. A challenge I have encountered is that in the JSON response received, there is an object such as "city":{"id":"1","name":"Washington"}. However, when the user leaves the city field ...

After successfully building with Vite, an error occurs stating "TypeError: can't convert undefined to object." However, during development with Vite, everything functions flawlessly

Currently, I am utilizing Vite in conjunction with React and Typescript for my project. Interestingly, when I execute 'vite dev', the live version of the website works flawlessly without any errors showing up on the console. However, things take ...

Even after installing npm3, the npm -v command continues to display version 2.x.x

As I delve into the world of Angular 2, I learned that it requires npm version 3.x.x. Despite installing npm3 with the command npm install -g npm3, when I check my npm version using npm -v, it still shows as 2.15.8. Strangely, running npm3 -v displays vers ...

Retrieve: Type 'string | undefined' does not match the parameter type 'RequestInfo'

When using the fetch function, I encountered an error with the "fetchUrl" argument: Error: Argument of type 'string | undefined' is not assignable to parameter of type 'RequestInfo'. This is the code snippet where the error occurred: ...

Encountering Error ENOENT while running Gulp Build Task with SystemJS in Angular 4

UPDATE: 2020.02.13 - It seems like another individual encountered the same issue, but no solution was found. Check out Github for more details. An array of GulpJS errors is emerging when attempting to construct an Angular 4 Web App with SystemJS. The str ...

Rewriting URLs in Angular 2

I am a beginner in Angular 2 and I am currently working on a project that requires URL rewriting similar to that of ' '. In Zomato, when you select a city, the city name appears in the URL like ' ', and when you select a restaurant, t ...

How can I set custom mappings in Elasticsearch to index specific parts of a jsonObject?

I am dealing with a JsonObject that looks like this: { "success": true, "type": "message", "body": { "_id": "5215bdd32de81e0c0f000005", "id": "411c79eb-a725-4ad9-9d82-2db54dfc80ee", "type": "metaModel", "title": "testchang", "authorId": "5 ...

What is the best practice for inserting typescript definitions and writing them when the object already has a pre-existing definition?

Apologies for this question, as I am struggling to find the necessary information due to my limited understanding of Typescript. I have integrated a jquery plugin called typeahead and added a global variable named bound on the window object for communicati ...

What separates the act of declaring a generic function from explicitly declaring a type for that very same generic function?

Here are two instances demonstrating the use of a generic function: function myGenericFunction<TFunc extends Function>(target:TFunc): string { return target.toString(); } Based on this response, this represents a declaration for a generic funct ...

Unable to translate the Json String into Java objects

I'm facing difficulties in converting the Json String to a Java Object After validating the Json format, it appears to be correct. @JsonIgnoreProperties(ignoreUnknown = true) public class DevPol { private String id; private Header header; ...

Issue with unit testing a ViewportRuler in Angular 2 Material Library

I am currently working on an Angular2 component that includes a tab control from @angular/material. During testing of my component (refer to the simplified code below), I encountered the following error: Error: Error in ./MdTabHeader class MdTabHeader - ...

Attempting to manipulate arrays by using the json_query method

I'm experiencing difficulties with using the json_query function to filter arrays based on a specific key value. When providing the direct path, this is the API result that is displayed: ok: [localhost] => { "msg": [ { ...

Checking for String Const Type in TypeScript

In my code, I have a custom type called Admin with two possible values: 'ADMIN' or 'AGENT'. There is a function that retrieves the user role from local storage: return localStorage.getItem('role'); I am looking to verify if ...

JQuery WCF Service is returning a 400 Bad Request response

I developed a WCF web service in ASP.NET 4.5 using VS2012 that delivers a JSON response successfully via the built-in webservice client. The endpoints are correctly configured in the Web.config file. However, I encountered an issue on the client side with ...

Issues encountered with returning a JSON object while utilizing a webservice (.asmx) in ASP.NET

I am currently utilizing an asp.net web service .asmx for the transportation of JSON data. However, I seem to be encountering issues with the following code: $.ajax({ type: "POST", url: "../../App_Code/jsonWebService/getValue", ...

Pass the API_BASE_URL parameter from the Angular 7 configuration

Currently, I am developing an Angular 7 Application using es6 Javascript and Swagger integration. My current challenge involves adding the configuration to APP_INITIALIZER in the app.module file: export class SettingsProvider { private config: AppConfi ...

"Exploring the world of TypeScript Classes in combination with Webpack

If I create a TypeScript class with 10 methods and export a new instance of the class as default in one file, then import this class into another file (e.g. a React functional component) and use only one method from the class, how will it affect optimizati ...

Angular 5 is throwing an error of TypeError: i28.ɵd is not a constructor

When I run the angular application in AOT mode using ng serve --aot, I encounter an error. It's important to note that there are no errors when building the application in AOT mode, but this error occurs in the browser when I access the application UR ...

The error message "Type 'Dispatch<SetStateAction<undefined>>' cannot be assigned to type 'Dispatch<SetStateAction<MyType | undefined>>'" appears in the code

I'm encountering challenges while creating a wrapper for useState() due to an unfamiliar error: Type 'Dispatch<SetStateAction>' cannot be assigned to type 'Dispatch<SetStateAction<VerifiedPurchase | undefined>>' ...

PHP's json_encode function does not escape the single quote character

I am currently facing an issue with parsing a JSON encoded object in JavaScript. When I use JSON.parse(word_array);, it throws an error saying Uncaught SyntaxError: Unexpected identifier. Upon investigating, I discovered that the object word_array is miss ...