如何通过点击传递参数来过滤和获取json数据文件?

时间:2018-04-27 14:51:38

标签: json angular filter binding

我有两个json文件:

test.json

[{
    "id": 1,
    "name": "Home"
  },
  {
    "id": 2,
    "name": "Test"
  }
]

test2.json

[{
    "id-cat": 2,
    "name": "Test 1"
  },
  {
    "id-cat": 1,
    "name": "Test 2"
  }
]

form.component.ts

import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { ButtonComponent } from '../atomic/button.component';
@Component({
    templateUrl: 'form.component.html',
    styleUrls: ['form.component.scss']
})
export class FormComponent {
    data: Object[];
    data2: Object[];
    constructor(private http: Http) {
        this.http.get('../assets/data/test.json')
            .subscribe(res => this.data = res.json());
    }
    private loadComponent = false;
    loadMyChildComponent(id: Number) {

        // missing code

        this.loadComponent = true;
    }
}

form.component.html

<ul>
    <li *ngFor="let d of data" (click)="loadMyChildComponent(d.id);">
        {{ d.name }}
    </li>
</ul>
<div *ngIf="loadComponent">
    <ul>
        <li *ngFor="let x of data2">
            {{ x.id-cat }}
        </li>
    </ul>
</div>

当我点击第一个列表时,我想根据传入的id加载 test2.json 数据。与此文件的id-cat相同。

如何绑定它?

1 个答案:

答案 0 :(得分:0)

你可以这样做:

test2.json

    [{
        "idcat": 2,
        "name": "Test 1"
     },
     {
       "idcat": 1,
       "name": "Test 2"
    }]

HTML

  <ul>
    <li *ngFor="let d of data" (click)="loadMyChildComponent(d.id);">
      {{ d.name }}
  </ul>
  <div *ngIf="loadComponent">
    <ul>
      <li *ngFor="let x of data2">
        {{ x.idcat }}
      </li>
    </ul>
  </div>

TS

export class FormComponent {
    data: Object[];
    data1: Object[];
    data2: Object[];
    constructor(private http: Http) {
        this.http.get('../assets/data/test.json')
            .subscribe(res => this.data = res.json());
        this.http.get('../assets/json/test2.json')
            .subscribe(res => this.data1 = res.json());
    }
    private loadComponent = false;

    loadMyChildComponent(id: Number) {

        // missing code

        this.loadComponent = true;
        this.data2 = this.data1.filter(res => res['idcat'] == id)
    }
}