0

On my test Angular 5 web client, on this HTTP call to my Java Jax-RS REST server I expect a return of data as array of type - PlayerRecord. (It is a simple class with a few fields).

 this.http.get<PlayerRecord[]>(this.url)
        .subscribe(data => this.onDataSuccess(data), 
                    err => this.errorHttp.set(err));

I am handling the data in the below function with parameter that expects data to be again an array of type - PlayerRecord:

playerRst: PlayerRecord[];

private onDataSuccess (data: PlayerRecord[]) {
    this.playerRst = data;
    console.log(this.playerRst.length);
    console.log(this.playerRst[0]);
    ...
}

Now, if the result has 2 or more elements in the array, I do get the expected array of data fine, HOWEVER, if I get only 1 record from the server, 'data' is no more an array and the steps in the onDataSuccess function fail.

Can you please explain why TypeScript can't keep an 1 element array as array or what I am missing, and how to work around this? Thank you.

2
  • Can you please include the response data. Commented Jan 21, 2018 at 22:24
  • 1
    99% that its server is sending one object instead of array. Commented Jan 21, 2018 at 22:24

1 Answer 1

2

The problem is likely your backend.

If a query such as get player record can returns multiple records then your backend should return a list even if that list contains a single element otherwise you will have problem like this due to response being parsed.

It doesnt make any sense to have a service call that sometime returns a single object and other time a list of object and then angular expecting an array of object to map.

Sign up to request clarification or add additional context in comments.

1 Comment

Good point. I should have looked a at the server end, what it returns. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.