Nirmal581 Nirmal581 - 2 months ago 11
TypeScript Question

Angular2 Array.prototype.map() failing when single object in array

The below code works fine, when the response returns MORE than 1 object in Json array. Note the Json structure expected is a array of Address objects referenced by property field "address". In other words (addresses.address) below references an Array.

public getAddressByPersonName(personName: string): Observable<Address[]> {
return this.http
.get(API_URL)
.map(response => {
const addresses = response.json();
if (addresses)
return (addresses.address).map((address) => new Address(address));
return null;
})
.catch(this.handleError);


}

When only ONE address is found, the response returns Json with single Address object. However I get below error during runtime.


TypeError: addresses.address.map is not a function


The JSON string returned is:
{
"address": {
"addressId": "1",
"addressLine1": "5 Bayberry Close",
"personName": "Dr John",
"route": {
"routeId": "100",
"routeName": "45 Main Street",
"updateBy": "admin",
"updateDate": "2017-07-03T17:48:33-04:00"
},
"updateBy": "admin",
"updateDate": "2017-07-03T18:10:27-04:00"
}
}


What is the reason for above runtime error ?

Answer Source

If I understand correctly you are trying to map an object, but the map function is only for arrays.
What you can do is check if the given response is the expected array response or not and wrap the object inside an array in case it's already one.
as followed:

getAddressByPersonName() {
  return this.http.get(API_URL)
    .map(response => {
      const addresses = response.json();
       if (addresses) {
         if(!Array.isArray(addresses.address)) {
           addresses.address = [addresses.address]
         }
           return (addresses.address).map((address: Address) => new Address(address));
       }        
       return null;
   })
}