Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" 
    }
like image 841
Jamil89 Avatar asked Aug 28 '26 23:08

Jamil89


1 Answers

just do this

{{data?.elemento}}
like image 60
Rahul Singh Avatar answered Aug 31 '26 12:08

Rahul Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!