从json文件中提取数据并使用按钮显示它

时间:2017-09-15 07:44:02

标签: json angular

我正在尝试从json文件中提取数据并显示它,但我无法继续该程序,因为我缺乏编码Angular的经验。

目前使用Angular 4.3,它使用HttpClientModule。

app.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
    title = '?';
    data;

    constructor(private http: HttpClient) {
    }

    ngOnInit(): void {
        this.http.get('/src/app/students.json')

    }

    chgTab1() {
        this.title = "Changed Title";
    }

    chgTab2() {
        //Want to display the items from json file
    }

}

students.json

[
    {"id": "3", "mame": "Dama"},
    {"id": "1", "mame": "ASD"},
    {"id": "2", "mame": "Chris"},
    {"id": "4", "mame": "Sass"},
]

1 个答案:

答案 0 :(得分:0)

    import { Component, OnInit } from '@angular/core';
import { Http,Headers } from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
    title = '?';
    data;
    showData = false;

  constructor(private http: Http) { }

  ngOnInit(): void {   
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    this.http.get('/assets/students.json', { headers: headers }).map(res => res.json()).subscribe(data => {
    this.data = data;
})

  }

  chgTab1(){
    this.title ="Changed Title";
  }

  chgTab2(){
    //Want to display the items from json file

    this.showData = !this.showData;
  }

}

我编辑了整件事。它现在适合你。确保您在正确的位置拥有student.json的路径。我将其移至资产目录