-1

I know this is probably an easy solution. I am building an Ionic 3 app and was able to connect to a json data file and print the objects to the console, but I am unable to pass the item to my search function. The error I get on the page is Runtime Error - Cannot read property "filter" of undefined - I am guessing its because the item isn't being made available.

data.ts

import { Injectable } from "@angular/core";
import { Http } from "@angular/http";
import "rxjs/add/operator/map";

@Injectable()
export class Data {
  items: any;

  constructor(public http: Http) {
    this.http
      .get("./assets/data/plaques.json")
      .map(res => res.json())
      .subscribe(data => {
        this.items = data;
        console.log(data);
      });
  }

  filterItems(searchTerm) {
    return this.items.filter(item => {
      return (
        item.veteran_first.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1
      );
    });
  }
}
georgeawg
  • 48,608
  • 13
  • 72
  • 95
Charles Smith
  • 3,201
  • 4
  • 36
  • 80

2 Answers2

2

You're trying to access this.items before it's been initialized.

http.get is an asynchronous function, and this.items may not be set when you access filterItems.

I highly recommend reading this question/answer which will go into greater understanding of the asynchronous nature of javascript.

Blue
  • 22,608
  • 7
  • 62
  • 92
  • This may also be of help: https://stackoverflow.com/questions/11856778/asynchronous-constructor – Blue Dec 11 '17 at 20:44
-1

could you please wrap it with zone() like this :

this.zone.run(() => {
   this.items = data;
 });
MBehtemam
  • 7,865
  • 15
  • 66
  • 108