如何从json文件ANGULAR2中检索特定数据

时间:2017-03-21 21:58:39

标签: javascript json angular filter ionic2

这是一个Ionic 2项目 我想从本地json文件中检索特定数据。我用Google搜索了8个小时,仍然无法找到解决方案! 这是我的json文件

[{
    "favoris": true,
    "description": "HOLD (NE PAS SUPPRIMER, NE PAS PASSER HORS PROD)",
    "codeD": "D47433C-07",
    "ville": "Poitier",
    "datePhoto": "2017-06-10T15:50:00"
},{
"favoris": true,
    "description": "HOLD (NE PAS SUPPRIMER, NE PAS PASSER HORS PROD)",
    "codeD": "D47433C-07",
    "ville": "Poitier",
    "datePhoto": "2017-06-10T15:50:00"}]

我的模特:

export class Site {
  public favoris: boolean;
  public description: string;
  public codeD: string;
  public ville: string;
  public datePhoto: Date;}

我的服务:

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Site } from '../models/site.model';

import { Observable, ObservableInput } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class SiteService {
  private _siteUrl = 'api/sites/sites.json';
  constructor(public http: Http) {
    console.log('Hello Data Provider');
  }

  /**
   * return sites
  */
  getSites(): Observable<Site[]> {
    return this.http.get(this._siteUrl)
               .map(this.extractData)
               .catch(this.logError);
  }
  extractData(response: Response): Site[] {
    var data = <Site[]>response.json();
    data.forEach((d) => {
      d.datePhoto = new Date(d.datePhoto);
    });
    return data;
  }
  logError(error: Response, caught: Observable<Site[]>): ObservableInput<Site[]> {
    console.log(error);
    return Observable.throw(error);
  }


  /**
   * for the searchbar
  */
  filterItems(searchTerm): Observable<Site[]> {
    return this.http.get(this._siteUrl)
               .map(res:Response)           .filter(item=>item.codeD.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1 || item.description.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1)
               .catch(this.logError);

  }

代码工作正常,但是当我调用filterItems函数(搜索栏)时,我有这个错误无法创建未定义的

0 个答案:

没有答案