Ionic2 and dataDirectory


with ionic2 it’s possible to have access to cordova.file.dataDirectory ? I have an error : Cannot read property ‘dataDirectory’ of undefined when I am using LokiJS.


You must declare a variable at the beginning, it is not a local variable (within the function). Use immediately after your imports:

Declare var cordova: any;

And obviously it will only work on the emulator or on a device.

Running into the same problem while I copied the code from the docs (
Solution seems to be running the code for initialisation after device.ready has fired. Guess the docs can still be improved.

Beware the plataform.ready first and then, if you try to call cordova.file anywhere in your rootPage, you will still receive an undefined error.

If you need to use cordova.file in your rootPage, do the following

1. import the Platform module

import { Platform } from ‘ionic-angular’;

2. edit your constructor to get platform injected:

constructor(…, platform: Platform) {

3. add the following inside your constructor:

platform.ready().then( _ => {
console.log("cordova.file.dataDirectory: " + cordova.file.dataDirectory);
// load your database here
// update your model here

This works when using a persistence adapter in LokiJs.

P.S: this answer was completely modified to avoid getting Bananas.

Thank you rapropos for being such a motivator =), hope you take out the Banana now :sunglasses:

IMHO the previous post is bananas. Use ionic-native and inject a File object in your constructor and everything should be fine.

1 Like

IMO, any library that requires going through the hoops you described is broken, and fixing it should be the priority instead of perpetuating such kludgery. Perhaps you might want to weigh in on loki-js #531, which seems like it might be relevant.

just updated the answer to avoid committing kludgery, I have no idea of what this word means (haven’t found it online), maybe it was just a ‘Gambiarra’.

I’m still mystified as to why the standard ionic-native File shim (there’s an example using dataDirectory in those docs) isn’t sufficient.

In this specific case (LokiJS + adapter + Ionic 2), the persistence adapter seems to be broken (as you said) and it will not work.

By the way, the standard usage of File is not yet in the web surface, I just checked the code you pointed out and I had to update my entire application in order to use it. I feel like dealing with black magic sometimes when using Ionic 2.

Thanks for pointing it out. I always check the official Ionic docs, but sometimes it’s not enough.

If you’re referring to changes from calling static methods to injecting and calling object methods, that changed when ionic-native went to v3 a couple of weeks ago. It allows you to only include the plugin shims you are using, which can help shrink app build size a fair amount.

Exactly, I started the project in the end of February.
In case someone else get into this, check this link and this.