Search code examples
androidjsonpathionic-frameworkngcordova

ionic read a local json file with $cordovaFile


I'm trying to load a local json file stored like this:

www/json/config.json

var path = '/android_asset/www/json'; //<-i have tried lots of differnt path's without success
var fileName = "config.json";
console.log('url: '+path+fileName);
console.log('file there?: '+angular.toJson($cordovaFile.checkFile(path, fileName)) );

$cordovaFile.readAsText(path, fileName).then(function (success) {
  console.log('read success: '+angular.toJson(success));
}, function (error) {
  console.log('read error: '+angular.toJson(error));
});

I use ionic with the ngCordova plugin $cordovaFile... Does anyone have an advice? I just want to ship my app with a "default" json loaded...


Solution

  • You can't read the file in your www folder using $cordovaFile with that path, $cordovaFile get access to the file through file:// protocol.

    Because the default json file is located in the www folder. Here is some ways to do that:

    1. Copy all the JSON content and put it inside a javascript file, and get access to that file as a global variable. (must include this file to the index.html)

      var json = {myKey: "myValue"};
      
    2. Using $resource as a service (not tested):

      $resource('file:///android_asset/www/json/myJson.json', {}, {
          query: { method: 'GET', params: {}, isArray: true }
      })
      
    3. Using $http within your controller:

      $http.get('json/myJson.json')
      .success(function (data) {
          // The json data will now be in scope.
          $scope.myJsonData = data;
      });