Krish
Krish

Reputation: 33

How to use angular Local Storage using typescript

I'm on single page app using typescript and angular. I'm using ng.Resource to fetch data from webapi

productResource.get({ userName: login.userName, password: login.password }, (data: Models.ICompany) => {
    this.localStorageService.set<Models.ICompany>("CompanyData", data);
});

I've added angular-local-storage.d.ts file and also installed angularlocalstorage

but when I try to store the promise returned from webapi I'm getting an error "unable to get propery 'set' of undefined or null reference". Also I could not find 'set' / 'get' methods in angular-local-storage.js file. I'm guessing the error is producing because the 'set'/'get' methods are unknow in .js file.

Could you please help me to resolve this issue.

Or is there any best way to store the data in browser using angular.

Upvotes: 1

Views: 2689

Answers (1)

david.carm
david.carm

Reputation: 329

I was having some trouble using localstorage in typescript too. What I did was: I found a js file on github with some functions to access localstore. I wrote the same js file in Typescript and used that file. This has a cookie fallback.

here is the link to my version :

https://gist.github.com/davidcarm/eedb29feb25a7130d0f9ac01a7d11d3f (scroll to bottom)

once you imported the SimpleStore.ts file you just use these functions:

constructor(private simpleStore: SimpleStore){}
// to save a value
simpleStore.store('value_name',value);
// to access a value
simpleStore.store('value_name',undefined);
// to delete a value
simpleStore.store('value_name',null);

Cheers!

Upvotes: 2

Related Questions