我有两个类定义如下,
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()方法执行操作。
答案 0 :(得分:0)
您现在正在做的事情,不是使用
创建您的课程实例.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 class和this answer。