Jamil89
Jamil89

Reputation: 165

Angular 2 - get datas from a json file

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

Answers (3)

Always Learn
Always Learn

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

Sajeetharan
Sajeetharan

Reputation: 222582

Just do,

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

Upvotes: 0

Rahul Singh
Rahul Singh

Reputation: 19622

just do this

{{data?.elemento}}

Upvotes: 1

Related Questions