【问题标题】:Unable to get object properties from http get method in angular 4无法从角度 4 中的 http get 方法获取对象属性
【发布时间】:2018-09-01 19:02:58
【问题描述】:

我有两个类定义如下,

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 () {

    }
}

另一个类是,

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 () {}
}

我从 http get 方法获取一个 JSON 对象,调用如下,

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 );
            }
          }
        );
}

这是该方法的 JSON 输出,

[
    {
        "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
    }
]

但是当我运行应用程序时,调用 http 方法时编写的控制台语句给出了输出

未定义

对于像parking_id,cycles这样的属性,但是对于其他2个属性,即地址和纬度,给出了正确的输出。 请纠正我哪里错了,JSON输出正确映射到位置对象?如果没有,我哪里出错了,请建议我阅读一些文章来解决这个问题。 注意:我无法理解 .map(),.subscribe() 函数对 angular4 中的 http.get() 方法的作用。

【问题讨论】:

  • 您使用的是HttpHttpClient
  • map 运算符用于以所需格式解析您的响应,并返回一个应订阅的可观察对象
  • 我正在使用 httpClient。
  • 如果你使用 angular >=4.2.3 这意味着你不需要map operator 因为新的HttpClient默认格式化响应JSON所以我们不再需要解析它使用 response.json()

标签: json angular angular-httpclient


【解决方案1】:

你现在做的不是创建你的类的实例,用

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

您只是说您期望是与您的班级相匹配的响应。您需要明确地将您的响应映​​射到您的班级。有几种方法可以做到这一点。你可以直接做..

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

但是创建某种序列化程序或创建类构造函数会更容易。这里有一些想法:How do I cast a JSON object to a typescript classthis answer

【讨论】:

  • 我明白了逻辑,但在这里我不是在处理一个类的单个对象,这里它自己的响应是我想要的对象数组。您提供的链接也适用于单个 JSON 对象,我正在尝试为我的案例实现,但无法实现,请帮助我。
猜你喜欢
  • 1970-01-01
  • 2019-02-04
  • 1970-01-01
  • 2018-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多