Search code examples
cordovaangularcordova-pluginsionic2ngcordova

ngCordova writeFile does not exist on type File error


I am building an Ionic2 app and I have successfully managed to create a local file using the 'ngCordova' plugin.

However, the function writeFile(..) listed on: http://ngcordova.com/docs/plugins/file/ doesn't seem to be supported by the same plugin which I used to create the same file.

This is the piece of code that is not working.

File.writeFile(this.getFilePath(), 'feedback.txt', data, true);

where File.writeFile is highligted with a message 'Unresolved function or method writeFile'.

When I build my app. the error that appears is:

Error TS2339: Property 'writeFile' does not exist on type 'typeOf File'

Any ideas if the Cordova plugin no longer supports this function or if the function is succeeded by another one, which I can't seem to be able to find?

Thank you!


Solution

  • Ionic 2 doesn't use ngCordova, instead it uses Ionic Native.

    Ionic Native has it's own File wrapper class but this is currently missing the .writeFile() implementation, track the related GitHub issue here #264

    For now you can use the .createFile() method of the Ionic Native File wrapper which should return a fileEntry object in the promise allowing you use some native file plugin code to write to the file.

    Example

    File.createFile(this.getFilePath(), 'feedback.txt', true).then((fileEntry) => {
    
        fileEntry.createWriter((fileWriter) => {
    
            fileWriter.onwriteend = () => {
                console.log('File writer - write end event fired...');
            };
    
            fileWriter.onerror = (e) => {
                console.log('file writer - error event fired: ' + e.toString());
            };
    
            fileWriter.write(data);
        });
    

    Update

    I believe the File class now has a .writeFile() method which should be used instead of my example code, but I haven't gotten around to trying it yet.