Utilizing Http to Retrieve JSON Data in Ionic 3

Struggling with Ionic, trying to fetch data from a JSON File using HTTP, but encountering a strange error.

https://i.sstatic.net/L2nVo.png

Below are the relevant code snippets :

src/pages/subhome/line/line.ts (The Subhome consists of multiple nested 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's the JSON file content:

src/pages/subhome/line/line.json

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

The goal is to display the JSON commands in the console for logging purposes. Thanks in advance!

Answer №1

Transfer your JSON file to the assets directory, and access it using the following code:

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

Answer №2

When making requests to remote servers, HTTP methods are commonly used. However, these methods are not typically utilized to call files within your application. To pass data between pages, you can employ a method similar to the following:

this.navController.push(SecondPage, {
    param1: 'firstname', param2: 'lastname'
});

For a detailed tutorial on passing data between pages in Ionic 2, refer to this link

If your goal is to access JSON data, it may be beneficial to store it in a variable or utilize local storage as demonstrated below:

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

Remember to import and inject as shown in the code snippet below:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using jQuery to fetch and display content from an external webpage

Is there a more effective method for loading an external web page on the same server? I've experimented with .load() and .get(), but they only load the page after the PHP script is finished. I've also used an iFrame, which displays the informatio ...

Preventing scrolling in one div while focusing on another div

I am currently in the process of creating a website that functions as a single page site. The main feature of the site is a masonry grid of images. When a user clicks on an item, a detailed panel slides in from the left. Once the panel is closed, it slide ...

Using Testcafe to extract the value attribute of a hidden input element

Is there a way to retrieve the value of an <input>, especially what is contained within its value attribute even if the input is not visible? I am using testcafé, but it seems like this could be a challenge. Does anyone have any suggestions or opti ...

"When working with Vue projects, an error may occur stating "Parsing error: No babel config file detected" if the IDE is not opened at

Encountered an issue in VS Code with a Vue project, where if the project is not opened at the root directory, babel.config.js fails to load causing confusion for the IDE. https://i.sstatic.net/pupVh.png All my files display an error on the initial charact ...

Tips for adjusting the property of an object that has been added to an array?

I have created an object. { "heading": [{ "sections": [] }] } var obj = jQuery.parseJSON('{"header":[{"items":[]}]}'); Then I add elements to the sections var align = jQuery.parseJSON('{"align":""}'); obj["he ...

Discovering the art of line breaks

Imagine I have a random block of text displayed in a single line, like this: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Due to various reasons such as width settings or text-zoom, the text may display as two or more lines on the viewer&apos ...

Is there a way for me to view the specific details of a country in my listview after I have chosen it?

I have a JSON file that contains data about countries, including cases and deaths caused by COVID. In my MainPage list view, I successfully display a list of countries. However, I now aim to show the details of each country when a user clicks on a specific ...

Creating dynamic routing functionality in Angular 8 allows for a more personalized and

I am struggling with setting up routing in Angular 8. Here is how I am trying to do it: 'company/:id/activity' 'company/:id/contacts' However, I am not receiving any params in the activatedRoute: this.activateRoute.params ...

``There is an issue with the onsubmit property that prevents the opening of

I have encountered an issue with my forms that has me stumped. Despite searching online for help, I can't seem to figure out why my implementation is not working as intended. The concept is straightforward. I've embedded a form within a JSP page ...

Serialize a series of select boxes to optimize for AJAX POST requests

To better explain my issue, let's consider a simple example: Imagine I have a form that collects information about a user: <form action="#" method="post" id="myform"> <input type="text" name="fname" /> <input type="text" name= ...

Switching from using a computed property in Vue 2 to implementing the Vue 3 Composition API

I am currently in the process of updating my Vue 2 application to Vue 3 and I have been exploring how to work with computed properties using the Composition API in Vue 3. One particular challenge I am facing is migrating a Vue 2 computed property that pro ...

What is the best way to create individual clickable images that open up a modal window for each one?

Currently, I have created a function that is able to map images from an array in Next.js using react-bootstrap. The function is functioning as expected, however, my goal is to add an onClick function to each image so that when clicked, it opens up in a new ...

Is it better to Vuex - manipulate store item twice, trigger new items, or perform transformations within components each time they are mounted?

I am considering performing two separate transformations on a single, large store item and then saving the results as two new store items. For instance: setEventsData: (state, data) => {...} // main huge master object // perform transformations on it an ...

Developing a fresh Outlook email using a combination of javascript and vbscript

I have created a custom HTML page with fields and a button to fill out in order to generate a new Outlook mail item. To format the body of the email using HTML, I am utilizing VBScript to create the new mail item. <script> function generateEmail() { ...

Save information from an excel file into a MySQL database using PHP by converting it to JSON format

Currently, I have a situation where I need to transfer two columns of data from an excel spreadsheet to a MySQL database (currently hosted locally). To accomplish this task, I am converting the spreadsheet data into a JSON string and then sending it to a P ...

Display a div in JQuery along with all of its associated label elements

Here is my HTML code: <div id="summarySpan" style="padding-left: 20px" hidden> <label id="currentStatusSummary" style="padding-left: 20px" /> <br /> <label id="currentMonitoringSummary" style="padding-left: 20px" /> < ...

When using Jquery, input can be appended on the last child element when a key

I am new to JavaScript and want to enhance my page's functionality using jQuery. Here is my current HTML: <div class="input_fields_wrap"> <div><ul class="inputList"></ul></div> </div> My goal ...

The search bar fails to display all pertinent results when only a single letter is inputted

How can I create a search functionality that displays array object names based on the number of letters entered? When I input one letter, only one result shows up on the HTML page, even though the console.log displays several results. The desired output is ...

Request with content Type multipart/form experienced Error 406

I encountered an issue with my axios request in Express const formData = new FormData(); formData.append("file", fs.createReadStream(file.path)); formData.append("requestid", '123456'); const options = { method: 'POST& ...

Implementing code to scroll and play multiple videos simultaneously using JavaScript and jQuery

This solution currently only works for one video, but it needs to be able to handle multiple videos (TWO OR MORE) <html> <head> <script src="https://code.jquery.com/jquery-1.8.0.min.js" integrity="sha256-jFdOCgY5bfpwZLi ...