2017-06-05 84 views
3

如何從角度2項目中的JSON獲取數據?我試過(下面的代碼),但這不起作用。也許我忘了一些細節...非常感謝回答Angular 2 - 從json文件中獲取數據

Ps。我需要在我的html上顯示包含在json文件中的「uno」。

app.component.ts:

 import { Component } from '@angular/core'; 
    import {Http} from '@angular/http'; 

    @Component({ 
     selector: 'app-header', 
     templateUrl: '../partials/app.header.html', 
     styleUrls: ['../css/partials/app.header.css'] 
    }) 
     export class AppComponent { 
      title = 'app works!'; 
      data; 
      constructor(private http:Http) { 
       this.http.get('app/header.json') 
       .subscribe(res => this.data = res.json()); 
      } 
     } 

app.module.ts:

import { BrowserModule } from '@angular/platform-browser'; 
    import { NgModule } from '@angular/core'; 
    import { FormsModule } from '@angular/forms'; 
    import { HttpModule } from '@angular/http'; 
    import { AppComponent } from './app.component'; 

    @NgModule({ 
     declarations: [ 
     AppComponent 
     ], 
     imports: [ 
     BrowserModule, 
     FormsModule, 
     HttpModule 
     ], 
     providers: [], 
     bootstrap: [AppComponent] 
    }) 
    export class AppModule { } 

app.header.html:

<header> 
    {{title}}//this works 
    {{elemento}}//here i want to show "uno" included in json file 
    ... 
</header> 

header.json:

{ 
     "elemento": "uno" 
    } 
+0

您應該優先考慮發佈的第一個 – Sajeetharan

回答

1

只是這樣做

{{data?.elemento}} 
+0

我可以知道downvote的原因 –

+0

在我看來沒有理由 – Picci

+0

它不起作用...我試圖... – Jamil89

0

只要做,

<header> 
    {{title}} 
    {{data?.elemento}} 
</header> 
0

get方法應該返回所以使用RX JS觀察的模式 就像這樣:http://davidpine.net/blog/angular-2-http/

import { Component } from '@angular/core'; 
 
    import {Http} from '@angular/http'; 
 
    import * from rxjs; 
 

 
    @Component({ 
 
     selector: 'app-header', 
 
     templateUrl: '../partials/app.header.html', 
 
     styleUrls: ['../css/partials/app.header.css'], 
 
     providers:[] 
 
    }) 
 
     
 
    export class AppComponent { 
 
      title = 'app works!'; 
 
      data :any; 
 
      constructor(private http:Http) { 
 
       this.http.get('app/header.json') 
 
       .subscribe(res => this.data = res.json()) 
 
       .map((res: Response) => <observable[]>response.json())    
 
          .catch(this.handleError); 
 
      } 
 
     } 
 
<header> 
 
    {{title}} 
 
    {{data?.elemento}} 
 
</header>