Michel_
Michel_

Reputation: 137

Filter results using Angular HttpClient

I use Angular5 with HttpClient. I created a service to fetch data from an JSON API URL.

This works perfect.

But now, I want to restrict the results with one criteria (spots.lat must be > minlat and < maxlat).

I try using map and forEach (see below the code part between ?????) but it doesn't work. How can I correct this?

...
import { HttpClient } from '@angular/common/http';
export interface Spot {
    lat: number,
    lng: number,
    spotname: sring
}
tempspots: <Spot[]>

@Injectable()
export class SpotService {
   private spoturl = '<JSON SERVICE URL>';
   constructor(
      private http: HttpClient,
      ...
   ) {}
   onGetAllSpots(minlat : number, maxlat : number) : Observable<Spot[]> {
      return this.http
      .get<Spot[]>(this.spoturl)
// ?????
      .map(spots => {
          spots.forEach(spot => {
             if (spot.lat > minlat && spot.lat < maxlat) {
                this.tempspots.push(spot);
             }
          })
          return this.tempspots;
      })
// ?????
   }
}

Upvotes: 3

Views: 4852

Answers (2)

Dev
Dev

Reputation: 115

Shorter version

.map(spots => spots.filter(spot => spot.lat > minlat && spot.lat < maxlat))

Upvotes: 0

Reza
Reza

Reputation: 19903

change your code to this, it should work

.map(spots => {
          const tempspots: <Spot[]> = [];
          spots.forEach(spot => {
             if (spot.lat > minlat && spot.lat < maxlat) {
                tempspots.push(spot);
             }
          })
          return tempspots;
      })

Another way is using filter

.map(spots => {
              return spots.filter(spot => { 
                  return spot.lat > minlat && spot.lat < maxlat;
              })
          })

Upvotes: 1

Related Questions