Angular 2 - 从json文件中获取数据
问题描述:
如何从角度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"
}
答
只要做,
<header>
{{title}}
{{data?.elemento}}
</header>
答
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>
您应该优先考虑发布的第一个 – Sajeetharan