当前位置:  开发笔记 > 编程语言 > 正文

如何将对象推送到angular2和typescript中的数组?

如何解决《如何将对象推送到angular2和typescript中的数组?》经验,为你挑选了1个好方法。

我已经定义了一个数组如下,

markers: marker[] = [
    {
      lat: 51.673858,
      lng: 7.815982,
      label: 'A',
      draggable: true
    }
  ];

我从休息服务获取数据并将新对象推送到标记.

private data: any;
  findLocation(): void {
    let result;
    result =   this.geoService.loaddata(this.location)
     .subscribe(data => {
       result = data;
       console.log(result);
       this.markers.push({'lat':results[0].geometry.location.lat,'lng':results[0].geometry.location.lng})
     });
  }

它抛出一个错误说文件:

消息:'类型的参数'{'lat':any; }'不能分配给'marker'类型的参数.类型'{'lat'中缺少属性'lng':any; } ''

结果是

{"results":[{"address_components":[{"long_name":"Colombo","short_name":"Colombo","types":["locality","political"]},{"long_name":" Colombo","short_name":"Colombo","types":["administrative_area_level_2","political"]},{"long_name":"Western Province","short_name":"WP","types":[" administrative_area_level_1","political"]},{"long_name":"斯里兰卡","short_name":"LK","类型":["country","political"]}],"formatted_address":"科伦坡,斯里兰卡","几何":{"bounds":{"northeast":{"lat":6.9812866,"lng":79.8900852},"southwest":{"lat":6.862390700000001,"lng":79.8223258}} ,"location":{"lat":6.9270786,"lng":79.861243},"location_type":"APPROXIMATE","viewport":{"northeast":{"lat":6.980584400000001,"lng":79.8900852}, "southwest":{"lat":6.8625113,"lng":79.8225192}}},"place_id":"ChIJA3B6D9FT4joRjYPTMk0uCzI","types":["locality","political"]}],"status":"OK "}

AJT82.. 12

您已订阅了数据result,而不是results.

private data: any;
  findLocation(): void {
    let result;
    // no use for "result" below
    // result = this.geoService.loaddata(this.location)
    // use the following instead
    this.geoService.loaddata(this.location)
     .subscribe(data => {
       result = data;
       console.log(result);
       this.markers.push({'lat':results[0].geometry.location.lat,'lng':results[0].geometry.location.lng})
     });
  }

所以你的推动应该是这样的:

this.markers.push({'lat':result[0].geometry.location.lat,'lng':result[0].geometry.location.lng})
         });

然而,这也将抛出一个错误,因为在标记你也宣布labeldraggable,所以你需要推值的属性了.



1> AJT82..:

您已订阅了数据result,而不是results.

private data: any;
  findLocation(): void {
    let result;
    // no use for "result" below
    // result = this.geoService.loaddata(this.location)
    // use the following instead
    this.geoService.loaddata(this.location)
     .subscribe(data => {
       result = data;
       console.log(result);
       this.markers.push({'lat':results[0].geometry.location.lat,'lng':results[0].geometry.location.lng})
     });
  }

所以你的推动应该是这样的:

this.markers.push({'lat':result[0].geometry.location.lat,'lng':result[0].geometry.location.lng})
         });

然而,这也将抛出一个错误,因为在标记你也宣布labeldraggable,所以你需要推值的属性了.

推荐阅读
pan2502851807
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有