【发布时间】: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() 方法的作用。
【问题讨论】:
-
您使用的是
Http或HttpClient? -
map运算符用于以所需格式解析您的响应,并返回一个应订阅的可观察对象 -
我正在使用 httpClient。
-
如果你使用 angular >=4.2.3 这意味着你不需要
mapoperator 因为新的HttpClient默认格式化响应JSON所以我们不再需要解析它使用 response.json()
标签: json angular angular-httpclient