0
votes

I'm currently working on a basic angular2/spring website. My goal is to get array of products form my spring backend;

This is how I import the data in my angular component:

 this.http.get<Produkt[]>('/get-produkty').subscribe(data => this.produkty = data);

where http is instance of HttpClient.

produkt interface:

 interface Produkt { nazwa: string; typ:string; cena:number;}

My spring method:

@RequestMapping(value = "/get-produkty")
public Produkt[] getNames() {
    return  dao.getProduktyAsTab();
}

produkty is arrayList of type Produkt, I'm trying to convert it to Array. It works fine as long as I convert my list to array like this:

public Produkt[] getProduktyAsTab() {
    Produkt[] produktyTest = new Produkt[10];
    this.produkty.toArray(produktyTest);
    return produktyTest;
}

But it doesn't when I try to do it like this:

public Produkt[] getProduktyAsTab() {
    Produkt[] produktyTest = (Produkt[]) this.produkty.toArray();
    return produktyTest;
}

I receive response code 500.

HttpErrorResponse {headers: HttpHeaders, status: 500, statusText: "OK", url: "http://localhost:8080/get-produkty", ok: false…}

How do I fix that? Why is this happening?

1
What error do you get by spring?baao
Spring's jackson mapper should automatically cast any list in spring as a json array. Have you tried to return the list as is?LookForAngular
Thanks a lot LookForAngular. Now I'm returning the list and it works.user8339412

1 Answers

0
votes

Possibly this.produkty is not castable to Produkt[] and you are getting class cast error.