Search code examples
jsonangularangular-httpclient

Unable to get object properties from http get method in angular 4


I have two classes defined as follows,

export class Cycle {
    lock_id: number;
    bicycle_id: number;
    qr_code: number;
    latitude: number;
    longitude: number;
    status: number;
    battery_level: number;
    is_locked: number;
    is_active: boolean;
    last_date_updated_on: Date;
    last_location_updated_on: Date;

    constructor () {

    }
}

And another class is,

import { Cycle } from './Cycle';
export class ParkingLocation {
    parking_id: number;
    latitude: number;
    longitude: number;
    parking_radius: number;
    max_cycle_limit: number;
    cycles: Cycle[];
    available_parking_space: number;
    available_cycles: number;
    address: string;
    area_id: number;

    constructor () {}
}

I am getting a JSON object from http get method which is called as follows,

return this.http.get(this.serverUrl + this.getParkingAreaUrl + '?parkingArea=' + this.myWebLocation.id, httpOptions)
        .subscribe( (data: ParkingLocation[]) => {
          // console.log(data);
          this.location = data;
           console.log(this.location);
          for ( let obj of this.location) {
            console.log(obj.parking_id);
            console.log(obj.address);
            console.log(obj.latitude);
            console.log(obj.cycles);
          }
        },
        (err: HttpErrorResponse) => {
            if (err.error instanceof Error) {
              console.log('Client-side error occured.');
            } else {
              console.log('Server-side error occured.');
              console.log( err );
            }
          }
        );
}

And here is JSON output from the method,

[
    {
        "parkingId": 1,
        "latitude": 12.958042,
        "longitude": 77.716313,
        "parkingRadius": 1,
        "maxCycleLimit": 5,
        "cycles": [
            {
                "lockId": "123654789123655",
                "bicycleId": 0,
                "latitude": 12.955596,
                "longitude": 77.714446,
                "status": 3,
                "batteryLevel": 500,
                "parking": {
                    "parkingId": 1,
                    "latitude": 12.958042,
                    "longitude": 77.716313,
                    "parkingRadius": 1,
                    "maxCycleLimit": 5,
                    "cycles": null,
                    "avilableParkingSpace": 0,
                    "availableCycles": 0,
                    "address": "HyperCity Market"
                },
                "qrCode": "1123",
                "lastDataUpdatedOn": null,
                "lastLocationUpdatedOn": null,
                "active": true,
                "locked": false
            }
        ],
        "avilableParkingSpace": 0,
        "availableCycles": 0,
        "address": "HyperCity Market",
        "areaId": 1
    }
]

But when i ran the application, the console statements written while calling http method is giving output

Undefined

For attributes like parking_id, cycles, but the correct output is given for other 2 attributes i.e for address and latitude. Please correct me where I am wrong, the JSON output is mapping correctly to location object? If not, where I am going wrong, Please suggest me some articles to read for the problem. NOTE: I am unable to follow, what .map(),.subscribe() function will do to the http.get() method in angular4.


Solution

  • What you are doing now, is not creating instances of you class, with

    .subscribe( (data: ParkingLocation[]) => {
    

    you are just saying that what you expect is a response that matches your class. You need to explicitly map your response to your class. There are several ways to do that. You could do it longhand..

    // assuming you are using HttpClient:
    .map(response => response.map(x => new ParkingLocation(x.parkingId /** ....**/))
    

    But it would be easier to create some kind of serializer or create a class constructor. Here are some ideas for that: How do I cast a JSON object to a typescript class and this answer.