Johansrk
Johansrk

Reputation: 5250

Angular 6 filter JSON

Hi I am having trouble filtering some JSON. My console.log in my component does not show anything. I would think it would display [2]

JSON file

[1,2,3,4,5]

Service

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map, filter } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})
export class SearchFlService {
  constructor(private http: HttpClient) {}

  getLabels = (searchValue: string) => {
    const fl = searchValue.substring(0, 3).toUpperCase();

    return this.http.get('/assets/data/fl/' + fl + '.json')
      .pipe(
        filter((items) => items === 2),
        map(
          response => {
            return response;
          },
          error => error)
      );
  }
}

component

this._searchFlService.getLabels(data.value.searchPlant)
        .subscribe(items => {
          console.log(items);
        });

Upvotes: 0

Views: 25262

Answers (1)

JayChase
JayChase

Reputation: 11525

You are filtering the observable stream not the items array.

    return this.http.get('/assets/data/fl/' + fl + '.json').pipe(
      map(items => {
        return items.filter(items => items === 2);
      }, error => error)
    );

*the above assumes that the get request returns the array [].

Upvotes: 3

Related Questions