Here's a guide on accessing information from a local JSON file and displaying it on an HTML page using Ionic 2 with TypeScript

I have received a JSON file formatted like the following:

{
  "records": {
    "patients": {
      "day": "Today",
      "details": [
        {
          "name":"Diab",
          "stat":"Pending",
          "phno":"8197246465",
          "patNames":"Sandra Adams",
          "tests": [
            {"name":"MCHC","result":"positive"}
          ]
        }
      ]
    }
  }
}

Is there a way to display each key on an HTML page or how can I parse this using a service?

Thank you in advance.

Answer №1

To accomplish this, you can create a service provider

import {Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import 'rxjs/Rx';

@Injectable()
export class customService {
    constructor(public http:Http) {}

fetchData() {
    return this.http.get("YOUR_PATH_TO_THE_JSON_FILE")
        .map((res:Response) => res.json().YOUR_JSON_HEADER); //records in this case
  }
}

Include the service in your ts constructor and execute the method to process through the retrieved data

this.customService.fetchData().subscribe((data) => {
  console.log("data contents: ", data);
  this.myjsondata = data;
});

Ensure to declare the service provider in app.module.ts

If using promises, make modifications in your service as shown below:

load() {
    console.log('json request made');
    return new Promise(resolve => {
        this.http.get('assets/data/patient.json').map(response => {
            this.data = response.json();
            resolve(this.data);
        });
    });
}

Here, data is obtained and resolved into a promise. To utilize it in html, obtain the data in your component page like so:

this.customService.load().then((data) => {
      console.log("data content: ", data);
      this.patdata= data;
    });

You can now display the patdata in your html

<h1> {{patdata | json}} </h1>

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

Exploring the power of a mapped type within a tuple

Can TypeScript ensure the validity of key-value tuples in this function? function arrayToObject(array, mapper) { const result = {}; for(const item of array) { const [key, value] = mapper(item); result[key] = value; } return ...

Angular's unconventional solution to Firebase

I've been having trouble integrating Firebase with Angular. When I encountered an error stating that firebase.initializeApp is not a function, I hit a roadblock. const firebase = require("firebase"); (Previously, it was written as: import * as fireb ...

The Angular subscription gets triggered multiple times

I am currently subscribed to this service: login(): void { if (!this.loginForm.valid) { return; } const { email, password } = this.loginForm.value; this.authService.login(email, password).subscribe((res) => { if (res.ok) ...

Controlling table row validation in Angular 2

After populating users from the userservice, I have successfully rendered them in a textbox control within a table using *ngFor. Users are able to change the values in the textbox within the table. My current challenge is validating each row containing us ...

Troubleshooting problem with rxjs subscription impacting component UI refresh

Currently, I am diving deep into the world of rxjs Observables, Observers, and Subscriptions. In order to grasp their functionality better, I decided to experiment with a sample code that updates the UI with random numbers at intervals of 1 second. My ulti ...

Tips for setting unique base_url for separate environment instances in angular2

My index.html file in Angular2 has the following content: When I build it in default mode (development mode) using npm run build, I want it to have: <base href="/"> However, when I build it in production mode (npm run build --target=production), I ...

The inability to receive a response from the OpenAI API in NextJS is causing frustration

I tried following a tutorial to implement functionality in T, but I am facing issues with getting a response from the API. I am unsure if there has been an update to the OpenAI API that is causing this problem. Any assistance would be greatly appreciated. ...

Get ready for 10 AM with the RxJS timer function

I am trying to figure out how to schedule a method in my code using rxjs/timer. Specifically, I want the method to run at precisely 10 AM after an initial delay of 1 minute. However, my current implementation is running every 2 minutes after a 1-minute d ...

Utilizing the power of HTML5 drag and drop functionality in conjunction with Angular Material 2's md

When working with Angular Material 2 and attempting to enable reordering of list elements, I encountered an issue where the functionality works perfectly for li-tag but fails with md-list-item. Why is that? Here is a snippet of my template: <md-nav-li ...

Error detected in Vuetify project's tsconfig.json file - The configuration file does not contain any input entries

Having an issue with the tsconfig.json file in my Vuetify project. The first { is underlined in red and when hovered over, it displays the error message: No inputs were found in config file Sharing the content of the file below. tsconfig.json { // expe ...

Angular messaging service error TS2769: There is no overload that fits this call

Currently, I am attempting to utilize a messenger service to send products to the cart component. Within the 'Product' class, there are various product attributes stored. Although I managed to successfully log the product to the console in the ca ...

Creating customized JavaScript bundles with TypeScript - a beginner's guide

Our ASP.NET MVC application contains a significant amount of JavaScript code. To optimize the amount of unnecessary JS being loaded to the browser, we utilize the BundleConfig.cs file to create multiple bundles. On the View, we implement logic to determin ...

This TypeScript error occurs when the props are not compatible and cannot be assigned to

Hello fellow Internet dwellers! I am a novice in the world of coding and TypeScript, seeking some assistance here. I am attempting to extract an array of objects from props, transform it into a new object with specific information, and then return it - ho ...

The Typescript generics are unable to be assigned to type T

Take a look at my code snippet: interface IDoc { doSomething(): void } class IDocFoo implements IDoc { doSomething(): void { console.log('Do doSomething'); } } class IDocFactory { getIDocInstance<T extends IDoc>(): T { re ...

Issue with customizing border color in Mui text field

Why is the border color of the Mui textField not remaining black when the user enters or selects data for the input fields? It still shows blue as in the photo. Here is the code: enter image description here.Here is the code. I'm wondering why this i ...

Expanding the typings for an established component in DefinitelyTyped

Is there a way to define new typings for additional props in DefinitelyTyped? After updating the material-ui library with some new props for the SelectField component, I realized that the typings in DefinitelyTyped are outdated. Is it possible to extend th ...

Create, Read, Update, Delete post problems

I've been working on the front end of my MEAN project and everything seems to be going smoothly. When I make a post request to localhost with the user's first name, last name, email, and password, I receive a successful response. https://i.sstati ...

The child user interface component is failing to respond to keypress events within the parent component in an Angular project

I am facing a challenge in adding a keyboard shortcut to open a nested child UI Tab component through a keypress event. However, the Child nested tab can only be loaded after the Parent component is loaded first. Below is the structure of the UI tree: |-- ...

Encounter a Typescript error when dealing with "app.ws" while using express-ws

I have a small project in mind where I want to create a BabyCam that can be accessed from any web browser using a Raspberry Pi Zero. My plan is to set up a web socket using express-is to stream video to multiple clients. I'm utilizing the raspivid-str ...