Search code examples
angularrxjshttpclientsubscriberxjs-observables

Return the "long_name" for the item that has types "locality"


I'm trying to print out the long_name for the item that has types === "locality". I'm using Angular and httpClient, which makes an observable. I'm lost in the complexity of rxjs and js. Can anyone help?

Service:

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));
  }

Component:

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

I'm getting this in my 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"] },
];

In my component I'll need to save the value El Prat de Llobegrat, to then be used in html.


Solution

  • You are on the right track

    The next step is filtering

    And you can do it either during the pipeline of rxjs or after the value is already emitted

    I suspect you want it during the pipeline

    Then either extend the current map in the rxjs pipe procedure, or append another map to the chain, and add the filter there:

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

    or

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