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);
TypeError: addresses.address.map is not a function
{
"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"
}
}
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;
})
}