1

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.

Anil
  • 1,748
  • 8
  • 32
  • 67
  • you are using `Http` or `HttpClient`? – Vikas Mar 23 '18 at 07:24
  • `map` operator is used to parse your response in the desired format and it returns an observable which shall be subscribed – Vikas Mar 23 '18 at 07:26
  • i am using httpClient. – Anil Mar 23 '18 at 07:27
  • if you are using angular >=4.2.3 which means you don't require `map `operator because of The new `HttpClient` by default formats the response to JSON so we no longer need to parse it using response.json() – Vikas Mar 23 '18 at 07:27
  • see this https://blog.angularindepth.com/the-new-angular-httpclient-api-9e5c85fe3361 – Vikas Mar 23 '18 at 07:28
  • Yes, i am using Angular 4 which does not require res.json(), how can we do it, please give me an example. – Anil Mar 23 '18 at 07:28
  • check the sintax, parkingId is not the same parkin_id, adress is not in your json... – Eliseo Mar 23 '18 at 07:39
  • @Eliseo, I did not get you, please explain me. – Anil Mar 23 '18 at 07:46
  • your json object have a property **parkingId**, you're writing console.log(**parking_id**) – Eliseo Mar 23 '18 at 07:49
  • But, i am mapping the JSON output to a ParkingObject here, how does it matters? – Anil Mar 23 '18 at 07:55

1 Answers1

0

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.

AT82
  • 71,416
  • 24
  • 140
  • 167
  • i got the logic, but here i am not dealing with a single object of a class, here the response it self is an array of objects which i want. The links u have provided are also for a single JSON object, i am trying to implement for my case, but unable to do so, please help me. – Anil Mar 23 '18 at 16:02