Freak took me way too long to figure out how to import correctly LocalForage. For a long time, my code was compiling but I was facing āundefined errorsā while running it.
So here my solution to import and use LocalForage in a Ionic2 project:
Install localforage
sudo npm install localforage --save
Add typings support
typings install dt~localforage --save --global
And finally how to use it in an injectable provider/service.
Note localforage, at least in my case, could not be imported like I mostly do with āimport * as localforage from ālocalforageā;ā because this will lead to the error āundefinedā at runtime. To solve the problem it should be included thru require() defined first as Function.
import {Injectable} from '@angular/core';
declare var require:Function;
const localforage:LocalForage = require('localforage');
// My data model module containing my object class UserAccess
import {User} from '../../model/user/user';
@Injectable()
export class UserAccessStorageService {
constructor() {
localforage.config({
name: 'MyApp'
});
}
saveUser(user_data:User.UserAccess):Promise<User.UserAccess> {
return localforage.setItem('myapp_user', user_data);
}
retrieveUser():Promise<User.UserAccess> {
return localforage.getItem('myapp_user');
}
clear():Promise<void> {
return localforage.clear();
}
}