Typescript类嵌套json cat

时间:2018-01-16 18:24:13

标签: json typescript angular5

您好我已经嵌套了json尝试演员级但我错了。

类:   export class Location { address: String city: String country: String position:{ lat:String, lng:String, } markers:{ lat:String, lng: String, label:String, draggable: boolean, iconUrl: String } }

我的json代码用于在angular5

中强制转换类
placeMarker(pos) {
this.service.getGeocode(pos.coords.lat + "," + pos.coords.lng).subscribe(res => {
  var resp: any = res;
  console.log(resp)
  if (resp.results && resp.results.length > 0) {

    this.location.address = resp.results[0].formatted_address;
    this.location.position.lat = resp.results[0].geometry.location.lat;
    this.location.position.lng = resp.results[0].geometry.location.lng;

    resp.results[0].address_components.forEach(res=> {
      res.types.forEach(t=> {
        if (t == "administrative_area_level_1") {
          this.location.city = res.long_name;
        }
      });
    });
  }
})

}

当我在angular5中点击标记时出现以下错误,我可以设置地址但是this.location.position.lat无法设置。

core.js:1350 ERROR TypeError: Cannot set property 'lat' of undefined
at SafeSubscriber.eval [as _next] (carpetfields.component.ts:55)
at SafeSubscriber.__tryOrUnsub (Subscriber.js:239)
at SafeSubscriber.next (Subscriber.js:186)
at Subscriber._next (Subscriber.js:127)
at Subscriber.next (Subscriber.js:91)
at MapSubscriber._next (map.js:85)
at MapSubscriber.Subscriber.next (Subscriber.js:91)
at XMLHttpRequest.onLoad (http.js:1556)
at ZoneDelegate.invokeTask (zone.js:425)
at Object.onInvokeTask (core.js:4620)

1 个答案:

答案 0 :(得分:2)

您正在设置this.location.address,但未设置this.location.position。

您的代码应该是这样的:

this.location.address = resp.results[0].formatted_address;
this.location.position = {
   lat: resp.results[0].geometry.location.lat,
   lng: resp.results[0].geometry.location.lng
}