1

There are few solutions on SO, but apparently they are deprecated. Angular 2 changes all the time...

Im trying to fetch a json file to my file.

There's a items.json file.

I'm wondering if I am able to make this work in just one file? I mean, just inside the app.component.ts? app.component.ts file actually looks like:

import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { Injectable }     from '@angular/core';

@Component({
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})


@Injectable()
export class AppServices{

  constructor(private http: Http) {
    let obj;
     this.getJSON().subscribe(data => obj=data, error => console.log(error));
  }

  public getJSON(): {
    return this.http.get("./items.json")
      .map((res:any) => res.json())
  }
}

export class AppComponent {
    let items = getJSON();
  }
}

Or maybe I have to include a app.service.ts file? And drop there the code fetching the json? It was so easy to do it in Angular1, why they made this so complicated...

I'm looking for the shortest solution as it is possible I will upvote every answer. Thank u in advance

EDIT I got another code:

import { Component } from '@angular/core';
import { Http } from '@angular/http';

@Component({
  selector: 'watchlist',
  templateUrl: './watchlist.component.html',
  styleUrls: ['./watchlist.component.css']
})


export class WatchlistComponent {

  data;

  constructor(private http:Http) {
    this.http.get('items.json')
      .subscribe(res => this.data = res.json());
  }

}

How to load this data into my items variable?

1 Answers1

2

// A function You can declare an app

app() {
    return this.http.get('/config.json');
  }

 this.app().subscribe((data: any) => {
 }
mayur
  • 3,558
  • 23
  • 37