herhuf
herhuf

Reputation: 527

Reading content of json file in ionic app

I'm trying to build an app with ionic that reads data from a local `.json' file and uses this data to fill a page. But I'm already struggling with importing the file into the page. What I currently have is:

import { Component } from "@angular/core";

interface Entry {
    name:           string,
    telephone:      string
}

interface EntryList {
    entryList:  Array<Entry>;
}

@Component({
    selector:    'page-list',
    templateUrl: 'list.html'
})
export class ListPage {

    entryList: EntryList;

    constructor() {
        this.load_entries();
    };

    load_entries () {
        this.entryList = JSON.parse(
            // ?
        )
    };
}

The .json file contains entries like:

[
{"name": "Person A","telephone": "1234"},
{"name": "Person B","telephone": "12345"}
]

I don't know how to proceed from here on. What's the right way to get my data into the app?

Upvotes: 1

Views: 2403

Answers (1)

coturiv
coturiv

Reputation: 2970

Please try this:

constructor(public http: HttpClient) {
    this.load_entries();
};

load_entries(filePath: string) {  //filePath: 'assets/test.json'

    this.http
        .get(filePath)
        .subscribe((data) => {
           console.log(data);
        });
}

Of course, you have to import HttpClient first.

import { HttpClient } from '@angular/common/http';

Upvotes: 1

Related Questions