H. Doe H. Doe - 1 year ago 122
JSON Question

Fetching a json file in Angular 2

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


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

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

templateUrl: './app.component.html',
styleUrls: ['./app.component.css']

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
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

I got another code:

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

selector: 'watchlist',
templateUrl: './watchlist.component.html',
styleUrls: ['./watchlist.component.css']

export class WatchlistComponent {


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


How to load this data into my items variable?

Answer Source

// A function You can declare an app

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

 this.app().subscribe((data: any) => {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download