Dave
Dave

Reputation: 31

How can I map through objects in angular with subscribe method?

I am getting the locations as an array of objects from the nodejs backend. I have subscribed to it in the frontend in angular and it is returning the array of objects. How can I get the name property of each object? I am trying to do an auto filter with the autocomplete in angular.

COMPONENT file

getLocations(){
    this.locationService.getLocations().subscribe( (res )=> {
      console.log(res);
    })
  }

SERVICE FILE


  getLocations(): Observable<LocationTypes>  {
    const makeReqURL = `${this.apiURL}/`;
    const getLocations = this.http.get<LocationTypes>(makeReqURL, { })
    return getLocations;
  }

The image of the console log from the response in the front end.

enter image description here

Error after adding PIPE

enter image description here

Thank you in advance.

Screenshot with the undefined

enter image description here

ERROR Message

enter image description here

Upvotes: 0

Views: 665

Answers (1)

user16695846
user16695846

Reputation:

Solution: use pipe then tap to get names from response.

import { tap } from 'rxjs/operators';

getLocations() {
    this.locationService
    .getLocations()
    .pipe(tap((response: any) => {
        response.map((data: any) => {
            return console.log(data.name);
        })
    }))
    .subscribe();

}

Upvotes: 1

Related Questions