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

What is the best way to retrieve additional data from a JSON file on an Android device?

Aspiring to develop an Android application for a specific website, I encountered a challenge. The site only displays 10 posts per page, with additional posts spread across multiple pages. My goal is to implement a feature where, upon scrolling down, the ap ...

Establishing the initial state within the constructor of a React Component utilizing a generic state

I have encountered an issue with React and Typescript. I am working on a component that utilizes two generics for props and state. interface Props { foo: string; } interface State { bar: string; } class Foo< P extends Props = Props, S e ...

Attempting to retrieve information from a PHP array

When outputting this array as JSON: $events['data'] The result is: [ { "id":"3" } ] However, attempting to access the id directly throws an error Undefined index: id, using the following code: $events['data'][' ...

Change an XML file to a JSON dump in Python

Hello there! I am looking to convert an XML file into a JSON dump. I have already attempted the following: for i in cNodes[0].getElementsByTagName("person"): self.userName = i.getElementsByTagName("login")[0].childNodes[0].toxml() self.use ...

Resetting the selected value in an Angular2 select element after the user makes a change

I have a dropdown menu which the user can select an option from. Initially it has a default value and when the user makes a new selection, I need to ask for confirmation by showing a message "are you sure?". If the answer is NO, then I should revert back t ...

Can you explain the functionality of this Angular CLI instruction?

Can you explain the function of this command in the Angular command line? npx ng g s weather --flat false Referenced in: Angular 6 for Enterprise Ready Web Applications, page 61 ...

Why does Typescript's 'await' seem to not wait as expected?

Apologies for the rookie mistake, I am currently transitioning from a C# background to Ionic, which may be causing some confusion on my end. I'm working on retrieving a stored token from Ionic storage but I'm struggling with understanding promise ...

The Angular downgradeComponent feature is experiencing difficulties in its creation process

I recently set up a hybrid application using AngularJS and Angular 5 with downgradeModule. I successfully converted a small component from AngularJS to Angular, but unfortunately, it is not being created. I've added console.logs in different parts of ...

Simple steps for transforming an array into a JavaScript object

Here is an array resembling a JSON structure with n elements: const mainData = [ { phrase: "Phrase 1", categorynumber: 1, optionnumber: 1, }, { phrase: "Phrase 2", categorynumber: 1, optionnumber: 2, }, ...

ValidationPipes do not support specific body types

Just a quick question: I'm working on applying a ValidationPipe to a POST endpoint responsible for adding an invoice. Before adding the invoice, I need to validate the body. Here is what I have done: invoice.dto.ts import { ContractorDto } from &apo ...

SQL query for retrieving an email address embedded in a string

Could you assist me in creating a SQL query to extract the email address from a text field that contains a json object like the following? {"objectType":"Agent","mbox":"mailto:<a href="/cdn-cgi/l/email-protection" clas ...

Changing the color of an input field in Angular Material to red

Below is an example of Angular code where the mat-form will turn red automatically if no value is entered. <mat-form-field> <input matInput placeholder="Enter your email" [formControl]="email" required> </mat-form-field> In the scenar ...

``There is an issue arising from the interaction between EventEmitter and Custom

Working with an Angular 8.3.14 project. We have implemented an EventEmitter to communicate a string value to the parent component. Child Component Setup @Output() pepe = new EventEmitter<any>(); ngOnInit() { this.pepe.emit('pepe'); } ...

Tips for implementing logic on input values in Angular 4

How to increase a value from a form in app.component.html by 2 and display it <input type="number" class="form-control" [(ngModel)]="value" /> <!-- <p><button (click)="submit()" class="btn btn-warning btn-sm">Submit</button ...

Enhancing Selectpicker options in Angular using data fetched from a web service

Having trouble with updating a selectpicker element within a subscribe method. I've included the code snippets below: Here is my HTML code: <div class="form-group col-md-2 pull-right"> <label for="city">City</label> <select ...

:host-selector for Angular Material dialog

I am currently working with a dialog component provided by angular-material and I need to customize the appearance of the popup dialog. I am aware that there is some support for styling through the component generation: let dialogRef = dialog.open(MyDi ...

Having trouble connecting my chosen color from the color picker

Currently, I am working on an angularJS typescript application where I am trying to retrieve a color from a color picker. While I am successfully obtaining the value from the color picker, I am facing difficulty in binding this color as a background to my ...

Issue with Google Maps API - Error: google object is undefined

Currently, I am in the process of learning how to develop Google Maps by analyzing some basic examples provided by Google. In my Angular 9 application, I utilize Angular Google Maps to showcase a Google Map. However, as I implement this feature, I encounte ...

Is there a way to verify if the object's ID within an array matches?

I am looking to compare the ID of an object with all IDs of the objects in an array. There is a button that allows me to add a dish to the orders array. If the dish does not already exist in the array, it gets added. However, if the dish already exists, I ...

Tips for correctly displaying diacritics with Webpack and Typescript

While working on my project, I encountered an issue with diacritics marks (such as German or Polish characters) when using Webpack with Typescript. Unfortunately, the problem arises when trying to display these marks in the console or on a webpage. It seem ...