Handling Data

Learn how the PlacesService and StorageService services are implemented.

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 make the following amendments (highlighted):

Press + to interact
/**
* 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;
}
}

Explanation of the logic

This is a fairly simple service which, through the loadCountries() method, loads the list of European countries that the different Apple Store locations belong to.

Once the JSON country data ...