Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从json文件中提取数据并用按钮显示_Json_Angular - Fatal编程技术网

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

从json文件中提取数据并用按钮显示,json,angular,Json,Angular,我试图从json文件中提取数据并显示它,但我无法继续执行该程序,因为我缺乏编写代码的经验 目前使用Angular 4.3,它使用HttpClientModule 应用程序组件.ts import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-root', templateUrl:

我试图从json文件中提取数据并显示它,但我无法继续执行该程序,因为我缺乏编写代码的经验

目前使用Angular 4.3,它使用HttpClientModule

应用程序组件.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"},
]

我编辑了整件事。现在对你有用了。确保您的student.json路径位于正确的位置。我将其移动到资产目录

您的版本是否在4.0之前?由于某种原因,我无法从@angular/common/http获取导入头。我的错误。我已经更新了导入。您可以删除公共部分。还要导入RxJS还要确保在app.module.ts.Update中导入HttpModule:我无法获取json文件。获取404(未找到)无需担心。我刚刚启动了电脑,并为你做了测试。我已经更改了上面的答案,我可以确认它返回了数据。还有什么问题请告诉我。
    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;
  }

}