Search code examples
angulartypescripthttpangular-httpclient

Unable to understand how map works in Angular


I want to preface this by saying that I am an Angular noob. So I am working on an application that implements the typeahead feature and I am making a HTTP call via my Express backend deployed on GCP, to obtain the search results from the TMDB database based on the search keyword.

this.http
      .get<any>('https://hw8-308202.wl.r.appspot.com/search?search='+term).pipe(
        map(data => data
        ))
        .subscribe(data => console.log(data));

I get a response such as -

[
    {
        "id": 10255,
        "backdrop_path": "NA",
        "media_type": "movie",
        "title": "Ab-normal Beauty"
    },
    {
        "id": 1320678,
        "backdrop_path": "NA",
        "media_type": "person",
        "title": "NA"
    },
    {
        "id": 131563,
        "backdrop_path": "NA",
        "media_type": "person",
        "title": "NA"
    },
    {
        "id": 259172,
        "backdrop_path": "/iZfCRsA9wcTZ0yWsuhXSHe4krdy.jpg",
        "media_type": "movie",
        "title": "Beyond the Great Wall"
    },
    {
        "id": 115301,
        "backdrop_path": "NA",
        "media_type": "person",
        "title": "NA"
    },
    {
        "id": 107531,
        "backdrop_path": "NA",
        "media_type": "person",
        "title": "NA"
    },
    {
        "id": 1820070,
        "backdrop_path": "NA",
        "media_type": "person",
        "title": "NA"
    }
]

Now, afaik when I pass the above to map, it should iterate over each json, but it's treating the entire response as one iteration. I am unable to iterate over the individual results and extract just the title. How do I go about doing that?


Solution

  • You are referring to array.map. map in observable is different to it. You have to do like this.

    this.http.get<any>('https://hw8-308202.wl.r.appspot.com/search?search='+term).pipe(
       map(data => {
         const titles: string[] = [];
         for (const e of data) {
           titles.push(e.title);
         }
         return titles;
       })
    ).subscribe(data => console.log(data));