Convertin res.json() to a Array<Object>

Viewed 691

I have a java webservice that out puts a list of Json objects with this 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;
  }

And i have a Angular4 project that i want to retrieve this json and store in a Array. How should i do this?

Angular4 oferta model:

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>;  
}

Method that i can retrieve the list of json objects(works fine, when i console.log(getData) i recieve the list of json objects. :

   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'})
       }
        //console.log('passou aqui')


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

    })
    .then((ofertas: Oferta[]) => {
        console.log('terceiro then executado apos 3 sec , aguardando outra promisse ser resolvida')
        return ofertas;

    })
}

Now how can i convert this to a Array? Already tried this.oferta[] = res.json(); Wont let me.

///////////// This is how i call at home.component

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

this.ofertasService.getOfertas2()
.then(
  ( ofertas: Oferta[] ) => { this.ofertas = ofertas
    console.log('a funçao resolve() foi resolvida depois de 3 segundos')
  })
  .catch((param: any) => {
    console.log(param)
  })    
  }
2 Answers

You simply have to typecast the data provided your class property names match the json properties.

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

You will have to import the toPromise function from rxjs

Update: i was able to do it using this:
this.http.get(this.actionUrl) .map(res => res.json()) .subscribe( data => { this.ofertas = data; }, err => console.log('cant get ofertas'), () => console.log('FOi')

But only directly on my Home.component.ts, tried doing it with a method getData from my Oferta.service.ts, i cant use http in oferta.service, so not sure how im going to do this in a differente class apart from the component.

Related