【问题标题】:Return the "long_name" for the item that has types "locality"返回具有“locality”类型的项目的“long_name”
【发布时间】:2020-06-07 12:10:53
【问题描述】:

我正在尝试为具有types === "locality" 的项目打印long_name。我正在使用 Angular 和 httpClient,这使得可观察到。我迷失在 rxjs 和 js 的复杂性中。 有人可以帮忙吗?

服务:

getGoogleGeo2(postalCode: string) {
    return this.http
      .get(`https://maps.googleapis.com/maps/api/geocode/json?address=${postalCode}ES&key=${api}`)
      .pipe(map(<T>(item) => item.results[0].address_components));
  }

组件:

this.geoService.getGoogleGeo2(postalCode).subscribe((item) => console.log(item));

我在我的 console.log 中得到了这个:

[
  { long_name: "08820", short_name: "08820", types: ["postal_code"] },

  { long_name: "El Prat de Llobregat", short_name: "El Prat de Llobregat", types: ["locality", "political"] },
];

在我的组件中,我需要保存值 El Prat de Llobegrat,然后在 html 中使用。

【问题讨论】:

    标签: angular rxjs httpclient subscribe rxjs-observables


    【解决方案1】:

    你在正确的轨道上

    下一步是filtering

    您可以在rxjspipeline 期间或在该值已经发出之后执行此操作

    我怀疑你在管道中想要它

    然后在rxjs pipe 过程中扩展当前map,或者将另一个map 附加到链中, 并在那里添加过滤器:

    .pipe(
      map(<T>(item) => item.results[0].address_components.filter(value => value.types.includes('locality'))
    );
    

    .pipe(
      map(<T>(item) => item.results[0].address_components),
      // another item in the pipeline
      map(values => values.filter(value => value.types.includes('locality'))
    )
    

    【讨论】:

    • 我想知道为什么要使用 includes('locality') 而不是 === "locality"?
    • types === 'locality' 将是检查types 是否持有原始string 作为值的正确方法,如:{..., types: 'locality'}。但是这里的情况是types 持有一个字符串数组,因此所需的操作是在数组inin 中搜索特定值。有几种方法可以检查数组中某项是否存在,最常见的有:Array.findIndex() - 并检查返回值是否大于-1,如:Array.findIndex(item =&gt; item === 'locality' ) &gt; -1,另一种是@ 987654336@基本一样
    【解决方案2】:

    Array find 将在其回调中返回与所需条件匹配的对象。例如:-

    this.geoService.getGoogleGeo2(postalCode).subscribe((item) => 
              console.log(item.find((value)=>value.types.includes("locality")).long_name)
    );
    

    【讨论】:

    • 请在您的答案中添加一些解释,以便其他人可以从中学习
    猜你喜欢
    • 2010-09-07
    • 2016-06-14
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 2015-09-19
    • 2010-10-10
    • 1970-01-01
    相关资源
    最近更新 更多