Angular 2 - get data from json file

How can I get data from JSON in angular 2 project? I tried (code below) but it doesn't work. Maybe I forgot some details ... Thanks a lot for the answer

Ps. I need to display in my html that "uno" is included in the 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" 
    }

      

+3


source to share


3 answers


just do it



{{data?.elemento}}

      

+1


source


Just do



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

      

0


source


The get method should return, so use the observable RX js pattern 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>
      

Run codeHide result


0


source







All Articles