Abhishta Gatya
Abhishta Gatya

Reputation: 923

Getting JSON Data using Http in Ionic 3

Having troubles with Ionic getting data from a JSON File via HTTP, I dont know what is the problem the error is quite strange.

error message in chrome devtool

here are the codes :

src/pages/subhome/line/line.ts (The Subhome contains a few folders of pages)

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
/**
 * Generated class for the LinePage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-line',
  templateUrl: 'line.html',
})
export class LinePage {

  commands: any[] = []

  constructor(public navCtrl: NavController, public navParams: NavParams, private http: Http) {
    this.http.get('line.json').map(res => res.json()).subscribe((data) => {
      this.commands = data.json();
      console.log(this.commands);
    })
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad LinePage');
  }

}

and here is the JSON file :

src/pages/subhome/line/line.json

{
	"commands": [{
			"title": "a",
			"desc": "b"
		},
		{
			"title": "a",
			"desc": "b"
		},
		{
			"title": "a",
			"desc": "b"
		},
		{
			"title": "a",
			"desc": "b"
		}
	]
}

What I'm trying to do is "logging" the JSON commands to the console Thanks in advance!

Upvotes: 0

Views: 1860

Answers (2)

Marouan
Marouan

Reputation: 217

move your JSON file to assets folder, and call it via

this.http.get('assets/line.json')

Upvotes: 1

shiben
shiben

Reputation: 23

HTTP methods are used to make calls to remote servers. As far as i know these methods are not used to call any file within your app For passing data among pages you can use something like this this.navController.push(SecondPage, { param1: 'firstname', param2: 'lastname' });

see tutorial here

If it is JSON data that you want to access, consider storing it in a variable or you can use the local storage like below

this.storage.set('myData', data);

Dont forget to import and inject

import { Storage } from '@ionic/storage';
constructor (public storage: Storage){}

Upvotes: 0

Related Questions