Reading local json file

Is there an easy way to read a local file. Specifically, I want to read a local JSON file and display a menu based on the data.

I’ve seen some methods, but they mostly use deprecated code.

Is there a better/modern way to do this?

Import the JSON in our current file. No need to make a network request. Export that JSON variable in that json file.

I’m not sure what you mean by “import the json in our current file”

I currently have it in the data directory underneath assets.

Oh I overlooked and thought it was about a file inside your ionic project. But, reading data from a local JSON file should also be easy. Also, what do you mean by deprecated code?

Here’s my home.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';


@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  data: any;


  constructor(public http: HttpClient) { }


  ngOnIt() {
    this.getData();
  }


  getData() {
      this.http.get('assets/data/menu1.json').map(res => res.json()).subscribe(res => {
            this.data = res.menuItems;
            console.log(this.data);
          },
          (err) => {
            alert('failed loading json data');
          });
    }

}

My home.html

<ion-header>
    <ion-toolbar>
        <div class="container">
            <div class="row">
                <div class="col-sm-4" style="text-align: left; vertical-align: center;" >
                        <img src="./../assets/images/lehigh-logo.svg" class="topLogo"/>
                </div>
                <div class="col-sm-4" style="text-align: center; vertical-align: center;" >
                    <h3>EMS PRO</h3>
                </div>
                <div class="col-sm-4" style="text-align: right; vertical-align: center;" >

                </div>
            </div>
        </div>
    </ion-toolbar>
</ion-header>

<ion-content>
    <ion-list>

        <ion-item button *ngFor="let item of data" [routerLink]="['/', item.itemPage]">
            <ion-icon slot="start" *ngIf="item.icon != ''" name="{{ item.icon }}}"></ion-icon>

            <ion-label text-wrap>
                <h3>{{ item.name }}</h3>
            </ion-label>


        </ion-item>

    </ion-list>
    
</ion-content>

menu.json

{
  "menuItems": [ {
    "id": "1",
    "name": "Protocols",
    "itemPage": "protocols",
    "icon": "bookmarks"
  },
  {
    "id": "2",
    "name": "Hospitals",
    "itemPage": "hospitals",
    "icon": "compass"
  },
  {
    "id": "3",
    "name": "Medications",
    "itemPage": "meds",
    "icon": "medkit"
  },
  {
    "id": "4",
    "name": "Calculators",
    "itemPage": "calcs",
    "icon": "calculator"
  },
  {
    "id": "5",
    "name": "Burn Tools",
    "itemPage": "burntools",
    "icon": "bonfire"
  },
  {
    "id": "6",
    "name": "References",
    "itemPage": "references",
    "icon": "book"
  },
  {
    "id": "7",
    "name": "Medical Command",
    "itemPage": "medcomm",
    "icon": "logo-whatsapp"
  }
  ]
}

Any help would be appreciated.

So this is there in your ionic project itself?

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

import { Observable } from 'rxjs/Observable';

import { Venue } from '@core/models';

@Injectable()
export class MockVenuesService {

  private readonly URL = 'assets/data/venues.json';

  constructor(protected httpClient: HttpClient) {}

  public list(): Observable<Venue[]> {
    return this.httpClient.get<Venue[]>(this.URL);
  }

}

Thank you for the help! I used your example and some other examples to create a service that reads in the local file!

Is this inside an ionic project itself? In that case, you would not need to make a network request at all.

I was able to push the functions into a service and read the file. Thank you everyone.

Here’s my service code:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class GetMenuService {

  constructor(private http: HttpClient) { }

  getMenu1(): Observable<any> {
    console.log('getMenu1');
    return this.http.get('../../assets/data/menu1.json').pipe(
        map(results => results['menuItems'])
    );
  }
}

You could just import this file instead of making a network request like below:

menu.ts (renamed from menu.json)

export const MENU = {
  "menuItems": [ {
    "id": "1",
    "name": "Protocols",
    "itemPage": "protocols",
    "icon": "bookmarks"
  },
  {
    "id": "2",
    "name": "Hospitals",
    "itemPage": "hospitals",
    "icon": "compass"
  },
  {
    "id": "3",
    "name": "Medications",
    "itemPage": "meds",
    "icon": "medkit"
  },
  {
    "id": "4",
    "name": "Calculators",
    "itemPage": "calcs",
    "icon": "calculator"
  },
  {
    "id": "5",
    "name": "Burn Tools",
    "itemPage": "burntools",
    "icon": "bonfire"
  },
  {
    "id": "6",
    "name": "References",
    "itemPage": "references",
    "icon": "book"
  },
  {
    "id": "7",
    "name": "Medical Command",
    "itemPage": "medcomm",
    "icon": "logo-whatsapp"
  }
  ]
}

Now, you can import in to your file like:

import { MENU } from '../../assets/data/menu';

Now you could MENU wherever you like in your ts file.