Search⌘ K
AI Features

Handling Data

Explore how to manage data in Ionic applications by loading JSON files for countries and locations, using Angular services to handle data retrieval and storage with Ionic Storage. Understand the role of TypeScript interfaces in enforcing data structure contracts to maintain data integrity and reduce errors throughout app development.

Getting data into the application

The src/app/services/places.service.ts class contains the functionality to load the following JSON files for the app:

  • The src/assets/countries.json file
  • The src/assets/locations.json file

These will be used to populate Ionic Storage with the European countries and Apple Store locations that our app will use as data sources.

Amendments to places.service.ts

Within the src/app/services/places.service.ts class, we ...

TypeScript 3.3.4
/**
* PlacesService
*
* This class manages the loading and supply of data from their respective JSON files
*/
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Country } from '../interfaces/countries';
import { Location } from '../interfaces/locations';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class PlacesService {
private countriesUri = 'assets/countries.json';
private locationsUri = 'assets/locations.json';
private countries: Array<Country> = [];
private locations: Array<Location> = [];
/**
* Creates an instance of PlacesService.
*/
constructor(private http: HttpClient) { }
/**
* Converts countries array into an Observable and returns that for
* the HomePage component to subscribe to
*/
public loadCountries(): void {
this.http
.get<Array<Country>>(this.countriesUri)
.pipe(
map((data: Array<Country>) => {
data.forEach((country: Country) => {
this.countries.push({
id : country.id,
country : country.country,
lat : country.lat,
lng : country.lng,
zoom : country.zoom,
active : country.active
});
});
})
).subscribe();
}
/**
* Return parsed Countries data
*/
public getCountriesFromJSON(): Array<Country> {
return this.countries;
}
/**
* Converts locations array into an Observable and returns that for
* the HomePage component to subscribe to
*/
public loadLocations(): void {
this.http
.get<Array<Location>>(this.locationsUri)
.pipe(
map((data: Array<Location>) => {
data.forEach((location: Location) => {
this.locations.push({
id : location.id,
country : location.country,
name : location.name,
address : location.address,
lat : location.lat,
lng : location.lng,
zoom : location.zoom,
active : location.active
});
});
})
).subscribe();
}
/**
* Return parsed Locations data
*/
public getLocationsFromJSON(): Array<Location> {
return this.locations;
}
}
...