Angular 4.x + Cordova : FileReader fails silently (white screen of death)

梦想的初衷 提交于 2019-12-04 14:10:35

EDIT

As stated long ago, I openned an issue on zone.js repository and zone.js owner quickly patched the code. You can avoid the pain of using my dirty hack just by importing zone.js/zone-patch-cordova inside your polyfills.

Original answer

While debugging this code I realized that the FileReader constructor was patched by both cordova and zone.js. From what I understood regarding zone.js patching is that it changes every "onProperty" (onload,onloadend,onerror) to its addEventListener(...) counterPart.

Module Name:

on_property

Behavior with zone.js :

target.onProp will become zone aware target.addEventListener(prop)

source

But cordova does not use the dispatchEvent(...) API to notify listeners operation has ended.

One solution might be to deactivate onProperty module from zone.js but it might break angular's behavior.

So this is how I coped with the situation :

read(file: FileEntry, mode: "text" | "arrayBuffer" | "binaryString" | "dataURL" = "text"): Observable<ProgressEvent> {
    return this.cdv.ready.flatMap(() => {
        return Observable.create(observer => {
            file.file(file => {
                let FileReader: new() => FileReader = ((window as any).FileReader as any).__zone_symbol__OriginalDelegate
                let reader = new FileReader();
                reader.onerror = (evt: ErrorEvent) => {
                    this.zone.run(() => observer.error(evt)); //never triggered
                };
                reader.onload = (evt: ProgressEvent) => {
                    this.zone.run(() => observer.next(evt)); //never trigerred
                };
                switch (mode) {
                    case "text":
                        reader.readAsText(file);
                        break;
                    case "arrayBuffer":
                        reader.readAsArrayBuffer(file);
                        break;
                    case "binaryString":
                        reader.readAsBinaryString(file);
                        break;
                    case "dataURL":
                        reader.readAsDataURL(file);
                        break;
                }
            });
        });
    });
}

The secret here is that zone.js keeps the original constructor in the __zone_symbol__OriginalDelegate property, so calling this will actually call Cordova's FileReader directly without zone.js patch.

This solution being a dirty hack,I have openned an issue on zone's repository

Edit :

Had the same problem with FileWriter (it internally calls a FileReader) so I wrote this little shim :

function noZonePatch(cb: () => void) {
    const orig = FileReader;
    const unpatched = ((window as any).FileReader as any).__zone_symbol__OriginalDelegate;
    (window as any).FileReader = unpatched;
    cb();
    (window as any).FileReader = orig;
}

then wrapped my calls to read/write operations :

write(file: FileEntry, content: Blob) {
    return this.cdv.ready.flatMap(() => {
        return Observable.create((out: Observer<ProgressEvent>) => {
            file.createWriter((writer) => {
                noZonePatch(() => {
                    writer.onwrite = (evt: ProgressEvent) => {
                        this.zone.run(() => {
                            out.next(evt);
                            out.complete();
                        });
                    };
                    writer.onerror = (evt) => {
                        this.zone.run(() => out.error(evt));
                    };
                    writer.write(content); // this is where FileReader is called internally
                })
            }, err => out.error(err));
        });
    });
}

read(file: FileEntry, mode: ReadMode = "text"): Observable<ProgressEvent> {
    return this.cdv.ready.switchMap(() => Observable.create((observer: Observer<ProgressEvent>) => {
        file.file(file => {
            noZonePatch(() => {
                let reader = new FileReader();
                reader.onerror = (evt: ErrorEvent) => {
                    this.zone.run(() => observer.error(evt));
                };
                reader.onload = (evt: ProgressEvent) => {
                    this.zone.run(() => observer.next(evt));
                };
                switch (mode) {
                    case "text":
                        reader.readAsText(file);
                        break;
                    case "arrayBuffer":
                        reader.readAsArrayBuffer(file);
                        break;
                    case "binaryString":
                        reader.readAsBinaryString(file);
                        break;
                    case "dataURL":
                        reader.readAsDataURL(file);
                        break;
                }
            });
        });
    }));
}

Something late to the party but I had to fix an Ionic3/Angular4 project with this exact problem and I found that the answer from @n00dl3 was on point but there is something of a race condition when an FileReader instance is created in a global service. Because sometimes zone did not patched yet the FileReader window object so no __zone_symbol__OriginalDelegate is found.

So what I did to always get the correct class is a little factory function that returns a FileReader instance:

function HackFileReader(): FileReader {
  const preZoneFileReader = ((window as any).FileReader as any).__zone_symbol__OriginalDelegate;
  if (preZoneFileReader) {
    console.log('%cHackFileReader: preZoneFileReader found creating new instance', 'font-size:3em; color: red');
    return new preZoneFileReader();
  } else {
    console.log('%cHackFileReader: NO preZoneFileReader was found, returning regular File Reader', 'font-size:3em; color: red');
    return new FileReader();
  }
}

and to use it just do :

const reader = HackFileReader();

I hope it helps somebody

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!