Reputation: 165
How can I get my datas from a JSON in an angular 2 project? I tried (code below) but this doesn't work. Maybe I forgot some details... thanks a lot for an answer
Ps. I need to display on my html that "uno" included in json file.
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"
}
Upvotes: 3
Views: 4713
Reputation: 672
get method should be returned so use RX js observable pattern just like this :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>
Upvotes: 0