adriancarriger / angularfire2-offline

🔌 A simple wrapper for AngularFire2 to read and write to Firebase while offline, even after a complete refresh.
https://angularfire2-offline.firebaseapp.com/
MIT License
207 stars 48 forks source link

Initialize with local data? #49

Closed pwespi closed 7 years ago

pwespi commented 7 years ago

Great package. I really appreciate your work!

Is there a way to initialize the localForage data with a local JSON file, such that when the app is opened for the first time while offline, there is already some data? I'm talking about an Ionic app on a smartphone, where I would like to ship the data as a JSON file with the app bundle and only use firebase for incremental updates.

adriancarriger commented 7 years ago

Hi @pwespi, I think you've come across a very important use case! 👍

Demo

Here is a demo (with code) of initializing app data from a Json file, and it does work offline! 🎉

Testing in browser

  1. Visit demo
  2. Go offline
  3. Open dev tools, go to IndexedDB, click localforage, then click keyvaluepairs, and clear the browser's local storage by clicking the lower righthand button screen shot 2017-07-30 at 7 53 44 am
  4. Reload demo

You should now see data initialized from the Json file!

Loading Json files

Loading Json files can be a little tricky using Typescript.

I just added the following to src/typings.d.ts:

declare module "*.json" {
  const value: any;
  export default value;
}

and imported it like this:

import jsonFile from './json-file-example.json';

These links may be helpful:

Initializing data

To initialize data, just add the data as you normally would with any Firebase list/object.

Example:

initializeData() {
  // Add list data from Json file
  this.groceries.remove(); // Remove is optional
  jsonFile.listExample.forEach(listItem => {
    this.groceries.push(listItem);
  });
  // Add object data from Json file
  this.car.set(jsonFile.objectExample);
}

Just call the initializeData method when you want to initialize your app's data.

Next steps

Next you might want to make sure that the data was not already initialized by adding a data object to your Firebase database. You would then check this data point before initializing data so that the Json file is only loaded once.