Troubleshooting issue with loading local json files in Ionic 3 on Android device

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.

Answer №1

It is recommended that you attempt

this.localApiUrl = "./assets/data";

No need to worry about the specific platform you are using.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving the maximum values from JSON data using D3

Currently, I am working with D3 and JSON data by using a function that looks like this: d3.json("http://api.json", function(jsondata) { var data = jsondata.map(function(d) { return d.number; }); After executing this, the value of the data becomes ["2", ...

The incredible power of the MongoDB $inc field

I am facing a challenge in writing a function that accepts a record id, an action (inc or dec), and a field name as a string to be incremented (can be 'likes', 'subs' or any other). The issue is that I am unable to find a way to replac ...

Tips for utilizing array.items in joiful validation?

Can someone provide an example code or a link on how to correctly use the joyful validation for array items? I attempted the array.items validation code using joyful, but I am not sure how to specify the items. Thanks in advance! ...

Encode the array in JSON format and return it as a string without any

Currently, I am in the process of developing a basic GUI for my Linux executable using HTML/JavaScript and PHP. However, I have encountered an issue when attempting to call my executable with the system function while passing a JSON string as a parameter. ...

Showing data in json format using Angular

I have designed a data table that showcases a list of individuals along with their information. However, when I click on the datatable, it keeps opening a chat box displaying the details of the last person clicked, overriding all other chat boxes. 1. Is t ...

Adding the API JSON response to the MetaInfo in Vue.js

i am dealing with a meta tag that has the following structure metaInfo () { return { title: 'my title', meta: [ { name: 'description', content: 'my description' }, ...

The component is no longer able to locate the imported element when it is being shared

Recently, I imported a component into the shared module in order to use it across 2 different modules. However, upon recompiling the app, an error message appeared stating that the jodit-editor, which is utilized by the shared component, is not recognized ...

Deduce the property type by the existence of the value

Here's a situation I'm trying to address in a simple way: if the entity prop is present, I want the onClick callback to receive the entity string, otherwise it should receive nothing. type SnakeOrCamelDomains = "light" | "switch" | "input_boolean ...

Passing an array to web service as parameters using Swift

I've been struggling to send an array object to a web service. Whenever I attempt to add the array to parameters, it throws an error. Despite trying various methods, none have proved to be effective. The goal is to include ("assignees" : newList) in ...

Why aren't Dependencies like RxJS being installed from package.json in the Dockerfile?

As I try to containerize my application for deployment on GCP, I have encountered an issue during local testing. It seems that the rxjs module (and possibly others) listed in package.json is not being installed properly. When building my Dockerfile, I rec ...

Delete JSON row columns efficiently without the need for iteration

Looking for a way to filter out specific data from your JSON object without looping through the entire thing? Here is a sample of the JSON data: [ { "cost":"KES 0.8000", "messageId":"ATXid_0fae395279b54d51519de5581230a7e ...

Assistance required for setting a value in a mat-select using Angular

Could really use some assistance resolving the issue with mat-select I'm aiming to establish the initial values by utilizing the following code snippet: orders: Order[] = [{"dish":"steak-0"},{"dish":"tacos-2" ...

Obtaining data from a JSON object

I'm attempting to extract the values using keys from the JSON response. I've tried the following methods but none of them have worked so far. 1.) string email = json.emailAddress; 2.) string email = json["emailAddress"].ToString(); Full Cod ...

Restricting enum type to only one member

enum Value { First, Second, } interface Data { value: Value number: number } interface SubData { value: Value.Second } function calculation(input: SubData){ return; } function initiate(){ const input : Data = { numbe ...

Converting nested JSON to a repeating CSV file using Powershell

Looking for a solution similar to what was discussed in the thread about converting nested JSON arrays into separate columns in a CSV file, but with a slight twist. Instead of exporting to flattened csv format, I need to export each nested value onto a sep ...

When working with Typescript and React, you may encounter an issue where an element implicitly has an 'any' type because the type 'State' has no index signature. This can lead to

In my current mini project, I am using Typescript and React. As someone new to Typescript, I am currently in the process of learning it. Within the project, I have a state defined as follows: type State = { field1: string, field2: string, field3: n ...

Unable to make custom font work in TailwindCSS and ReactJS project

I have incorporated a custom font into my projects using React, TypeScript, TailWind, and NextJS. The font file is stored in the /fonts directory with the name Glimer-Regular.ttf. To implement the font, I added the following code snippet to my global.css ...

Executing a component method from a service class in Angular

When trying to call a component method from a service class, an error is encountered: 'ERROR TypeError: Cannot read property 'test' of undefined'. Although similar issues have been researched, the explanations mostly focus on component- ...

Agents should only be initialized within a before function or a spec in Angular

Having trouble with my private function: private GetChargesByClient(clientId: number): Observable<any[]> { const ds = new Date(); const dateTocompare = new Date(ds.setFullYear(ds.getFullYear() - 1)); return this.getCharges(id).pipe(map(res => re ...

Browser inspect tool is failing to hit breakpoints when using USB-connected device

While troubleshooting my Ionic Capacitor application on a USB connected device, I noticed that my browser dev-tools (Chrome, Edge, Firefox) are not hitting my breakpoints in the source code. Interestingly, when I run the application on ionic serve, everyt ...