TypeScript Storing Files
The solution is simple, very simple, so, without further ado, let’s see some code, to keep things simple, I initially created a class called FileStore, all this class really needed in my opinion was two methods, one to simply store the files, another to simply retrieve the files, that’s it. I decided, since I was using Angular, what an appropriate time to take advantage of RxJS. So, to give you the solution, here you go;
To walk you through the code, it’s quite simple really, in order to store the file object(s) to HTML5 storage, all that’s really going on consists of converting these file objects to the custom POJO called BasicFileInformation. But in order to do this, we must take advantage of the FileReader API, by making use of the FileReader, we’re able to read the contents of the file as a data URL. But the only form of challenge here is that in order to do this, the FileReader’s method to do this is asynchronous, hence why I thought it suitable to take advantage of the observable that RxJS so kindly provides us. Once all of the files have been processed, the idea is to have your state management code elsewhere, there you can subscribe to this sotreFiles method & carry on like so. As I was using Angular, I wanted a nice way to load the files from HTML5 storage, hence the creation of the loadFiles method.
In the loadFiles method, again, very simple stuff, all that we’re doing here is essentially loading the file data by using the fetch API. Due to the fact that this is essentially an ajax request, that’s right, more asynchronous code, so, to keep things nice & consistent, I decided to return another observable object.