打字稿类嵌套json猫

Posted

技术标签:

【中文标题】打字稿类嵌套json猫【英文标题】:Typescript class nested json cat 【发布时间】:2018-06-25 12:52:33 【问题描述】:

您好,我有嵌套的 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

我在 angular5 中转换类的 json 代码

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】:

您正在设置 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

【讨论】:

以上是关于打字稿类嵌套json猫的主要内容,如果未能解决你的问题,请参考以下文章

将打字稿类转换为对象

typescript 打字稿类示例

typescript 打字稿类示例

typescript 打字稿类示例

访问打字稿类的成员变量是不是需要`this`?

如何从现有对象初始化打字稿类?