如何在角度2项目中从JSON获取数据?我试过(下面的代码),但这不起作用。也许我忘了一些细节......非常感谢答案
聚苯乙烯。我需要在我的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 :(得分:1)
就这样做
{{data?.elemento}}
答案 1 :(得分:0)
做,
<header>
{{title}}
{{data?.elemento}}
</header>
答案 2 :(得分: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);
}
}
&#13;
<header>
{{title}}
{{data?.elemento}}
</header>
&#13;