Transforming res.json() into an Array of Objects

I am dealing with a Java webservice that outputs a list of Json objects with specific properties:

public class Oferta {
private int id;
private String categoria;
private String descricao_oferta;
private String anunciante;
private double valor;
private boolean destaque;
private List<String> imagens;
  }

Now, I am working on an Angular4 project and need to retrieve this JSON data and store it in an Array. How should I go about achieving this?

This is the Angular4 model for "Oferta":

export class Oferta {
public id: number;
public categoria: string;
public titulo: string;
public descricao_oferta: string;
public anunciante: string;
public valor: number;
public destaque: boolean;
public imagens: Array<Object>;  
}

The method I have written to retrieve the list of JSON objects works fine - when I console.log(getData), I receive the list of JSON objects as expected:

   public getData(): Promise<Oferta[]>{

     this.ofertas = this.http.get(this.apiURL)
    .map((res: Response) => <Oferta[]>res.json())                        << ERROR WHEN CASTING

    return new Promise((resolve,reject)=>{
        let deu_certo = true
        if(deu_certo){
            setTimeout(() => resolve(this.ofertas),3000);

        }
       else{
           reject({codigo_erro: 404,mensagem_erro: 'Servidor nao encontrado'})
       }

    })
    .then(( ofertas: Oferta[]) => {
        console.log('second then')
        return new Promise((resolve2,reject2) => {
            setTimeout(() => {resolve2(ofertas )},3000)
        })

    })
    .then((ofertas: Oferta[]) => {
        console.log('third then executed after 3 seconds, waiting for another promise to be resolved')
        return ofertas;

    })
}

Now I am facing the challenge of converting this to an Array. I have already tried using `this.oferta[] = res.json();` but it won't allow me to do so.

///////////// This is how I call it in home.component

ngOnInit() { this.ofertas = this.ofertasService.getData()

this.ofertasService.getOfertas2()
.then(
  ( ofertas: Oferta[] ) => { this.ofertas = ofertas
    console.log('the resolve() function was resolved after 3 seconds')
  })
  .catch((param: any) => {
    console.log(param)
  })    
  }

Answer №1

To successfully retrieve and use the data, make sure that your class property names correspond to the JSON properties.

getData():Promise<Oferta[]>{
    return this.http.get(this.apiURL)
    .map((res: Response) => <Oferta []>res.json()).toPromise()
}

Do not forget to include the toPromise function from rxjs when working with this code.

Answer №2

Update: I managed to accomplish it by utilizing the following code snippet:
this.http.get(this.actionUrl) .map(res => res.json()) .subscribe( data => { this.ofertas = data; }, err => console.log('failed to retrieve ofertas'), () => console.log('Success')

However, I encountered difficulty when attempting to implement it within a method called getData in my Oferta.service.ts file, as I am unable to use http in oferta.service. Therefore, I am unsure on how to proceed and achieve this functionality in a separate class from the component.

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

Remove duplicate elements from a JSON array

How can I add each item in an array for each duplicate? Transform: [ { "uuid":"EE877ABD-932F-4B4C-AB23-B324363B0B60", "planning":[ { "uuid":"6D680178-9B05-4744-A004-163D4B3E1E84", "star ...

Arranging and refining elements in a list of documents that contain lists

My Desired Output: I am looking to display the expected results of processing documents using the mongoDB command. (Note: Some documents may not contain arrays.) Documents for Processing { "_id": ObjectId("60ddc26b03edfb7a6b424f10"), "mem ...

Managing the onChange event for a MaterialUI dropdown component

I'm encountering an issue with validating the MaterialUI TextField component (Country list) wrapped with Autocomplete. I am trying to use the onChange event to enable the Submit button when the country field is filled in. However, the problem arises w ...

Eliminate duplicate objects from arrays of objects by a specific key name

Here are some arrays of objects I am working with: var arr = [ {name: 'john', last: 'smith'}, {name: 'jane', last: 'doe'}, {name: 'johnny', last: 'appleseed'}, {name: 'johnson', ...

Convert a Treeview to JSON format and then convert it back to a Treeview through des

I want to convert a Treeview node into JSON format and then back into a Treeview. Within my code, I have a unique SubNode class that looks like this: Class SubNode: TreeNode { dynamic obj; } Essentially, every tree node will contain ...

Guide to importing a custom component into an Ionic 4 page

In Ionic 4, I have a page called IntroPage that utilizes a custom component named intro-task. When trying to use intro-task, Angular throws an error: Can't bind to 'active' since it isn't a known property of 'intro-task'. 1. ...

Validation with React Hooks does not function properly when used on a controlled component

I've recently started using react hook form and I've created a custom component based on material ui's autocomplete. The issue I'm facing is that react hook form isn't validating the field at all. Let me show you how the setup look ...

Creating a popup trigger in ReactJS to activate when the browser tab is closed

I am currently working on an enrollment form that requires customer information. If a user fills out half of the form and then attempts to close the tab, I want to trigger a popup giving them the option to save and exit or simply exit. While I have a jQue ...

Typescript: Implementing a generic function with the flexibility of an optional parameter

Having some difficulty writing a generic function with an optional parameter type Action<TParameters = undefined> = (parameters: TParameters) => void const A: Action = () => console.log('Hi :)') // This works as expected const B: ...

Hey there! I'm currently facing some difficulties with storing form input data into a nested json file

I have developed a Next.js application with a form component structured as follows: components/Form.js import { useState } from 'react' import { useRouter } from 'next/router' import { mutate } from 'swr' const Form = ({ for ...

Tracking events in Angular 4 using angulartics2 and Adobe Analytics: A step-by-step guide

I've been working on tracking page views in my Angular 4 application, specifically with Adobe Analytics. Currently, I am utilizing angulartics2 for this purpose. First step was adding the necessary script for Adobe Staging in my index.html page: &l ...

Arranging an array in Angular 7 with various states and numbers

Looking to tackle this array sorting issue in Angular 7, the data is fetched from the API: "Products": [ { "ProductCode": "MC30180", "Description": "Description_1", "NationalCode": "N.C. 0965", "Pend ...

Angular 2's subscribe method allows for actions to be taken in response to

There are two buttons, one of which is hidden and of type file. When the user clicks the first button, a confirmation dialog opens. Upon clicking "Ok" in the dialog, the second button should be clicked. The issue arises when all the logic in the subscribe ...

How to dynamically deserialize a Newtonsoft JSON into an object using VB.NET

ANSWER provided involves utilizing LINQ to JSON and the JObject for converting JSON into a usable object dynamically. Below is the code snippet that demonstrates this conversion, followed by the original query. 'Parse JSON string into a JObject acces ...

Maintain the text layout when copying and pasting from the Angular Application

After noticing that copying and pasting text from an Angular Application to a text editor like Microsoft Word results in losing the original format, I decided to investigate further. An example I used was the angular material website: https://material.ang ...

Querying data elements using Graphql mutations: a step-by-step guide

const MUTATION_QUERY = gql` mutation MUTATION_QUERY( $name: bigint! ) { insert_name( objects: { name: $name } ) { returning { id name } } } `; const [onClick, { error, data }] = useMut ...

What is the best approach for managing generic errors in a hybrid Rails 5 app that uses a mix of JSON APIs and HTML responses?

After spending an entire day experimenting with different methods, I still haven't achieved my goal and decided to seek help now... In my Rails 5 application, I have developed a JSON API based on the actual JSON API specifications. Additionally, it f ...

What is the process for interacting with a Node.js Web API using an Angular JS API?

Seeking assistance with converting HTML into JADE format, encountering issues with {{record.name}} not functioning correctly. This is preventing the fetching and printing of values. Below are the complete file details: Directory view can be seen here. JS ...

What is the best way to run two MySQL queries simultaneously using promises in a Node.js environment?

My goal is to merge JSON data returned from my node.js server based on the value of the first MySQL queries in array JSON format. If I want to execute two MySQL queries, I enable multipleStatements: true and the code looks like this: app.post('/prod ...

Creating a regular expression to capture a numerical value enclosed by different characters:

export interface ValueParserResult { value: number, error: string } interface subParseResult { result: (string | number) [], error: string } class ValueParser { parse(eq: string, values: {[key: string] : number}, level?: number) : ValueParse ...