-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
      );
    });
  }
}

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

-1

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

this.zone.run(() => {
   this.items = data;
 });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.