【问题标题】:Ionic observable pluck nested properties离子可观察采摘嵌套属性
【发布时间】:2018-05-16 13:00:29
【问题描述】:

我正在使用 Ionic 和 Observable httpClient 请求,并希望使用 pluck() 以我需要的格式获取数据。我有我想要的某种格式的 Google Place api 调用的 json 输出。

api输出格式:

{
  "html_attributions" : [],
  "next_page_token" : ...,
  "status" : "OK",
  "results" : [
      {
      "geometry" : {
        "location" : {
          "lat" : 52.693031,
          "lng" : -2.53443
        }
      },
      ...
    },
    {
      "geometry" : {
        "location" : {
          "lat" : 52.3841398,
          "lng" : -2.3740612
        }
      },
      ...
    },
  ]
}

所需格式:

[
  {
    "location" : {
      "lat" : 52.693031,
      "lng" : -2.53443
    }
  },
  {
    "location" : {
      "lat" : 52.693031,
      "lng" : -2.53443
    }
  },
  ...
]

我读到 here 应该可以在嵌套属性上使用 pluck()

我正在尝试的一个 sn-p:

let url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=' +
  this.location.latitude +
  ',' + 
  this.location.longitude + 
  '&radius='+this.radius + 
  '&type=park&key=' + 
  this.placeApiKey;

this.places = this.httpClient.get(url);

this.places
.pipe(
  pluck('results', 'geometry')
)
.subscribe(data => {
  console.log(data);
});

好像只能拔第一级,不能拔第二级。谁能指出我做错了什么。

【问题讨论】:

  • console.log(data)的输出是什么
  • @TjaartvanderWalt。当我同时使用 'results''geometry' 时,console.log 输出为 undefined
  • this.httpClient.get(url) 是异步的,您没有订阅 this.httpClient.get(url) 调用
  • 数组results 没有参数geometry。勇气正试图做一个someObject.results.geometry,而你想要的是someObject.results[0].geometry
  • @ibenjelloun。啊!好的,我明白我在哪里愚蠢了......那么我将如何使用 pipe() 实现我需要的格式?

标签: javascript angular ionic-framework rxjs observable


【解决方案1】:

您可以使用rxjs maparray map 获得所需的格式:

this.places
.pipe(
  map(places => places.results.map(result => result.geometry))
)

【讨论】:

  • 这对我有用。使用这两种类型的地图功能是否最佳?还是有更好的方法通过链接管道?
  • 即使同名,两个功能也大不相同。我认为仅使用 rxjs 管道函数是不可能的。
猜你喜欢
  • 2023-03-21
  • 1970-01-01
  • 2021-11-22
  • 2017-05-22
  • 2017-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-25
相关资源
最近更新 更多