2017-09-15 82 views
-3

我試圖從json文件中提取數據並顯示它,但是我無法繼續使用該程序,因爲我缺少編碼Angular的經驗。從json文件中提取數據並用按鈕顯示

當前使用的是使用HttpClientModule的Angular 4.3。

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"}, 
] 

回答

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的路徑。我將它移動到資產目錄

+0

4.0之前的版本是否是角?由於某些原因,我無法從@ angular/common/http獲取導入標題。 –

+0

我的不好。我已更新進口。您可以刪除公共部分。還要導入rxjs –

+0

還要確保在app.module.ts中導入HttpModule。 –

相關問題