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