如何使用 ionic 2 typescript 从本地 JSON 获取数据到 HTML 页面 [英] How to get the data from local JSON, to the HTML page using ionic 2 typescript

查看:13
本文介绍了如何使用 ionic 2 typescript 从本地 JSON 获取数据到 HTML 页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种类型的 JSON 文件.

I have this type of JSON file.

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

如何将每一个键带入 html 页面或如何使用服务解析这个键?

How to bring each and every key into the html page or how to parse this one using service?

提前致谢.

推荐答案

可以通过创建服务提供者来实现

You can do so by creating a service provider

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

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

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

在你的ts构造函数中定义服务,调用方法解析数据

Define the service in your ts constructor and call the method to parse through the data

this.yourService.getData().subscribe((data) => {
  console.log("what is in the data ", data);
  this.myjsondata = data;
});

确保在 app.module.ts 中定义服务提供者

Make sure to define the service provider in app.module.ts

对于您的情况下的承诺,请按如下方式修改代码:为您服务.

For promises as in your case modify the code as follows: In your service.

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

在这里,您正在获取数据并决心承诺.要在 html 中使用它,您必须在组件页面中获取数据,如下所示.

Here you are getting data and resolving to promise. To use this in html you have to get the data in your component page as follows.

this.yourService.load().then((data) => {
      console.log("what is in the data ", data);
      this.patdata= data;
    });

您现在可以在 html 中使用 patdata

You can now use the patdata in your html

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

这篇关于如何使用 ionic 2 typescript 从本地 JSON 获取数据到 HTML 页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆