Recently, I've been exploring the process of loading a local JSON data file in my project. I have stored my .json files in the /src/assets/data directory and here is the provider code snippet that I am utilizing:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/from';
import 'rxjs/add/observable/throw';
import { Platform } from 'ionic-angular';
/*
This is the generated class for the JsonProvider provider.
Check out https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more details on providers and Angular 2 DI.
*/
@Injectable()
export class JsonProvider {
private localApiUrl: string;
private remoteApiUrl: string;
constructor(public http: Http, private platform: Platform) {
if (this.platform.is('cordova') && this.platform.is('android')) {
this.localApiUrl = "file:///android_asset/www/data";
}
else {
this.localApiUrl = "assets/data";
}
}
GetLocalData(file: string): Observable<any> {
return this.http.get(`${this.localApiUrl}/${file}.json`)
.map(this.extractData)
.catch(this.handleError);
}
GetRemoteData(url: string): Observable<string[]> {
return this.http.get(`${this.remoteApiUrl}/${url}`)
.map(this.extractData)
.catch(this.handleError);
}
GetGareList(): Observable<any> {
return this.GetLocalData("gareList");
}
GetGara(Id: number): Observable<any> {
return this.http.get(`${this.localApiUrl}/gare.json`)
.map(res => {
let body = res.json();
if (body) {
return body.filter(x => { return x.Id == Id })[0];
}
else {
return {};
}
})
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || {};
}
private handleError(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
return Observable.throw(errMsg);
}
}
During testing in the local browser, everything works perfectly fine as the correct JSON data gets loaded. However, when attempting the same on an Android device, it only returns an error message:
0 - {"isTrusted":true}
I even tried removing the file:///
part but unfortunately, it still didn't resolve the issue of loading the file.