LocalStorage plugin with nativescript angular?


Hi. Does anyone have example code for using the local storage plugin with Nativescript Angular?

(the github readme is in vanilla javascript).

I am porting this question from an earlier discussion, because this is a slightly different issue (other discussion: Best Local Storage option?).

I would think it is straightforward to get this to work, but I keep getting errors. Here is what I’ve tried:

I downloaded the plugin ($ tns plugin add nativescript-localstorage). The plugin properly shows up in my node_modules.

I rebuilt ios just to be sure, and reran $ tns run ios

And have code like the following:


import { LocalStorage } from "nativescript-localstorage";
constructor( private localStorage: LocalStorage ) {...}

ngOnInit(): void {

    if (this.localStorage.getItem('myStorageKey') !=  null ){
        this.itemToShow = this.localStorage.getItem('myStorageKey')

I get the following error:

JS ERROR Error: Can't resolve all parameters for MyFileComponent: ([object Object], ?).

I have also tried other methods, like not specifying local storage in the constructor definitions:

import { localStorage } from "nativescript-localstorage";
constructor (){}

ngOnInit(): void {
   localStorage.setItem('testKey', 'hello there')

And that produces this error:

CONSOLE ERROR [native code]: ERROR TypeError: undefined is not an object (evaluating 'nativescript_localstorage_1.localStorage.setItem')
CONSOLE ERROR [native code]: ERROR CONTEXT [object Object]



Regarding you first method: Angular is not going to make any magic for us, we will have to explicitly define a Provider for anything that has to be injected as a dependency.

2nd method: It doesn’t do named export, it just exports a single object. You may import it like below, just as you must do in non angular apps, as shown in docs - end of day everything is just JavaScript.

import * as localStroage from 'nativescript-localstorage';
// Or
// Once imported with either of the syntax, it will be available globally in `global.localStorage` object

I would highly recommend you to spend nice time with basics of TypeScript / JavaScript and Angular.


The import syntax was the problem. Thanks for pointing it out. The following works:

import * as localStorage from 'nativescript-localstorage';
 ngOnInit(): void {
    localStorage.setItem('myStorageKey', 'hello there')