在JSON响应中从数组创建一个新的Observable

时间:2018-12-28 17:38:51

标签: angular rxjs

我正在使用Angular 7,并且有一个httpclient请求,该请求返回一个包含嵌套数组的JSON响应。我在将数组元素作为Observable而不是单个对象返回时遇到了麻烦。下面的代码提取数组并将其作为带有单个(数组)对象的Observable返回。

return (this.http.get(url)
  .pipe(
    pluck('candidates')
  )
);

我想要为每个数组元素返回一个带一个条目的Observable。代表性的JSON列在下面。

谢谢!

{"spatialReference":{"wkid":4326,"latestWkid":4326},"candidates":[{"address":"80305, Boulder, Colorado","location":{"x":-105.24280489999995,"y":39.983092300000067},"score":100,"attributes":{},"extent":{"xmin":-105.28580489999996,"ymin":39.940092300000067,"xmax":-105.19980489999995,"ymax":40.026092300000066}},{"address":"080305","location":{"x":70.684671556000069,"y":42.633023284000046},"score":100,"attributes":{},"extent":{"xmin":70.671671556000064,"ymin":42.620023284000048,"xmax":70.697671556000074,"ymax":42.646023284000044}},{"address":"80305","location":{"x":-107.45293038699998,"y":24.909200000000055},"score":100,"attributes":{},"extent":{"xmin":-107.88393038699998,"ymin":24.478200000000054,"xmax":-107.02193038699998,"ymax":25.340200000000056}},{"address":"080305","location":{"x":25.969188087000077,"y":43.900496861000079},"score":100,"attributes":{},"extent":{"xmin":25.968188087000076,"ymin":43.899496861000081,"xmax":25.970188087000079,"ymax":43.901496861000076}},{"address":"80305","location":{"x":23.74637722600005,"y":50.135623723000037},"score":100,"attributes":{},"extent":{"xmin":23.728377226000049,"ymin":50.117623723000037,"xmax":23.76437722600005,"ymax":50.153623723000038}},{"address":"80-305","location":{"x":18.55720020800004,"y":54.408705009000073},"score":100,"attributes":{},"extent":{"xmin":18.556200208000039,"ymin":54.407705009000075,"xmax":18.558200208000041,"ymax":54.409705009000071}},{"address":"803","location":{"x":120.28383000000008,"y":22.626259687000072},"score":98,"attributes":{},"extent":{"xmin":120.27383000000007,"ymin":22.61625968700007,"xmax":120.29383000000009,"ymax":22.636259687000074}}]}

1 个答案:

答案 0 :(得分:2)

我不知道为什么要这么做,但是from()从数组创建一个可观察对象,并发出数组的每个元素。所以你所需要的就是

return this.http.get<YourObject>(url).pipe(
  switchMap(o => from(o.candidates))
);