Git Product home page Git Product logo

ng2-webstorage's Introduction

ngx-webstorage

Local and session storage - Angular service

This library provides an easy to use service to manage the web storages (local and session) from your Angular application. It provides also two decorators to synchronize the component attributes and the web storages.

CircleCI

Index:


Migrate from v2.x to the v3

  1. Update your project to Angular 7+
  2. Rename the module usages by NgxWebstorageModule.forRoot() (before: Ng2Webstorage)

The forRoot is now mandatory in the root module even if you don't need to configure the library


  1. Download the library using npm npm install --save ngx-webstorage

  2. Declare the library in your main module

    import {NgModule} from '@angular/core';
    import {BrowserModule} from '@angular/platform-browser';
    import {NgxWebstorageModule} from 'ngx-webstorage';
    
    @NgModule({
    	declarations: [...],
    	imports: [
    		BrowserModule,
    		NgxWebstorageModule.forRoot(),
    		//NgxWebstorageModule.forRoot({ prefix: 'custom', separator: '.', caseSensitive:true }) 
    		// The forRoot method allows to configure the prefix, the separator and the caseSensitive option used by the library
    		// Default values:
    		// prefix: "ngx-webstorage"
    		// separator: "|"
    		// caseSensitive: false
    	],
    	bootstrap: [...]
    })
    export class AppModule {
    }
  3. Inject the services you want in your components and/or use the available decorators

    import {Component} from '@angular/core';
    import {LocalStorageService, SessionStorageService} from 'ngx-webstorage';
    
    @Component({
    	selector: 'foo',
    	template: `foobar`
    })
    export class FooComponent {
    
    	constructor(private localSt:LocalStorageService) {}
    
    	ngOnInit() {
    		this.localSt.observe('key')
    			.subscribe((value) => console.log('new value', value));
    	}
    
    }
    import {Component} from '@angular/core';
    import {LocalStorage, SessionStorage} from 'ngx-webstorage';
    
    @Component({
    	selector: 'foo',
    	template: `{{boundValue}}`,
    })
    export class FooComponent {
    
    	@LocalStorage()
    	public boundValue;
    
    }

Store( key:string, value:any ):void

create or update an item in the local storage

Params:
  • key: String. localStorage key.
  • value: Serializable. value to store.
Usage:
import {Component} from '@angular/core';
import {LocalStorageService} from 'ngx-webstorage';

@Component({
	selector: 'foo',
	template: `
		<section><input type="text" [(ngModel)]="attribute"/></section>
		<section><button (click)="saveValue()">Save</button></section>
	`,
})
export class FooComponent {

    attribute;

    constructor(private storage:LocalStorageService) {}

    saveValue() {
      this.storage.store('boundValue', this.attribute);
    }

}

Retrieve( key:string ):any

retrieve a value from the local storage

Params:
  • key: String. localStorage key.
Result:
  • Any; value
Usage:
import {Component} from '@angular/core';
import {LocalStorageService} from 'ngx-webstorage';

@Component({
	selector: 'foo',
	template: `
		<section>{{attribute}}</section>
		<section><button (click)="retrieveValue()">Retrieve</button></section>
	`,
})
export class FooComponent {

    attribute;

    constructor(private storage:LocalStorageService) {}

    retrieveValue() {
      this.attribute = this.storage.retrieve('boundValue');
    }

}

Clear( key?:string ):void

Params:
  • key: (Optional) String. localStorage key.
Usage:
import {Component} from '@angular/core';
import {LocalStorageService, LocalStorage} from 'ngx-webstorage';

@Component({
	selector: 'foo',
	template: `
		<section>{{boundAttribute}}</section>
		<section><button (click)="clearItem()">Clear</button></section>
	`,
})
export class FooComponent {

    @LocalStorage('boundValue')
    boundAttribute;

    constructor(private storage:LocalStorageService) {}

    clearItem() {
      this.storage.clear('boundValue');
      //this.storage.clear(); //clear all the managed storage items
    }

}

Observe( key?:string ):EventEmitter

Params:
  • key: (Optional) localStorage key.
Result:
  • Observable; instance of EventEmitter
Usage:
import {Component} from '@angular/core';
import {LocalStorageService, LocalStorage} from 'ngx-webstorage';

@Component({
	selector: 'foo',
	template: `{{boundAttribute}}`,
})
export class FooComponent {

    @LocalStorage('boundValue')
    boundAttribute;

    constructor(private storage:LocalStorageService) {}

    ngOnInit() {
      this.storage.observe('boundValue')
        .subscribe((newValue) => {
          console.log(newValue);
        })
    }

}

The api is identical as the LocalStorageService's


Synchronize the decorated attribute with a given value in the localStorage

Params:

  • storage key: (Optional) String. localStorage key, by default the decorator will take the attribute name.
  • default value: (Optional) Serializable. Default value

Usage:

import {Component} from '@angular/core';
import {LocalStorage, SessionStorage} from 'ngx-webstorage';

@Component({
	selector: 'foo',
	template: `{{boundAttribute}}`,
})
export class FooComponent {

	@LocalStorage()
	public boundAttribute;

}

Synchronize the decorated attribute with a given value in the sessionStorage

Params:

  • storage key: (Optional) String. SessionStorage key, by default the decorator will take the attribute name.
  • default value: (Optional) Serializable. Default value

Usage:

import {Component} from '@angular/core';
import {LocalStorage, SessionStorage} from 'ngx-webstorage';

@Component({
	selector: 'foo',
	template: `{{randomName}}`,
})
export class FooComponent {

	@SessionStorage('AnotherBoundAttribute')
	public randomName;

}

  • Serialization doesn't work for objects:

NgxWebstorage's decorators are based upon accessors so the update trigger only on assignation. Consequence, if you change the value of a bound object's property the new model will not be store properly. The same thing will happen with a push into a bound array. To handle this cases you have to trigger manually the accessor.

import {LocalStorage} from 'ngx-webstorage';

class FooBar {

    @LocalStorage('prop')
    myArray;

    updateValue() {
        this.myArray.push('foobar');
        this.myArray = this.myArray; //does the trick
    }

}

npm install

Start the unit tests: npm run test

Start the unit tests: npm run test:watch

Start the dev server: npm run dev then go to http://localhost:8080/webpack-dev-server/index.html

ng2-webstorage's People

Contributors

byrondover avatar dependabot[bot] avatar mikejhill avatar pillowpillow avatar ryzy avatar sconix avatar sherlock1982 avatar trentrand avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ng2-webstorage's Issues

__webpack_require__.i is not a function

I would like to use version 1.3.0 with angular 2.0.2 and typescript 2.0.3 and [email protected], but I got the error message that

__webpack_require__.i is not a function
on line
@SessionStorage('session_key') session_key: string;

I went back to 1.2.4 and it works well.

how to get value from local storage when the key is start with uppercase

First thanks for this good library.

I have a case that the key in the local storage is start with uppercase.
in my case is "Authorization" with capital "A"
and when I use the retrieve("Authorization") it return null.
I debug and found that the library change the key to lowercase.
is there a way to use capital to get value?

thanks

AoT Support

Firstly, this is a great library (one of the best for localstorage in my opinion).

It seems the library does not support aot, but this is hard to debug (Runtime compiler is not loaded). Does it support AoT? If not, are you planning to support it?

Better default values for @LocalStorage() Decorator

It would be nice to be able to set the default value for properties marked up with @localStorage().

Here is an example of an ideal usage from an AuthService.

@LocalStorage('AuthService.user')		  
protected user = ANONYMOUS;

Currently, if you set user, then reload the page local storage is overwritten with anonymous on object initialization.

I wish that if 'AuthService.user' was set user would be assign to it instead of ANONYMOUS on object construction. Alternatively, it would be nice to specify the default in the Decorator if it's not possible to maintain the TS default property value semantics like @LocalStorage('AuthService.user', ANONYMOUS)

Currently we work around this in our constructor as follows,

 let storedUser = this.storage.retrieve('AuthService.user');
    if (storedUser) {
      this.user = storedUser;
    } else {
      this.user = ANONYMOUS;
    }

which is a lot of boilerplate to carry around for a default value.

decorated properties unable to get localstorage value promptly during app initialization for Angular 4.0

It was fine before I upgrade my project to ng4.0.1

I have a APP_INITIALIZER provider in my app module. I do some data initialization in it. Previously all my services in this initialization process that have properties decorated with @LocalStorage() works perfectly fine and they are able to get initial values as long as my browser localstorage have the data needed.

But since I upgraded to angular 4.0, it can no longer get initial values in APP_INITIALIZER provider. They are undefined.

I upgraded ng2-webstorage to the newest version 1.6.2

(@LocalStorage() works fine when app initialization is finished)

Systemjs Import Error

I have been working for a while trying to get this project to load in and play nice with my project. It may be that I am no where near being an expert in systemjs but I kept getting an error of:

SyntaxError: Unexpected token <

It was a pretty generic error and it lead me to going through previous issues that have been closed until I stumbled across #1 where you explained to do the following for those using systemjs:

The last commit fix the errors and adds a compiled version of the library. If you're using systemjs you simply have to import the ng2-webstorage in you application via import {...} from 'ng2-webstorage/index'.

I attempted to do this but I found that my solution was importing the ng2-webstorage as you normally would (i.e. ng2-webstorage': 'npm:ng2-webstorage) but the tricky part was adding the following few lines to the packages object:

packages: { 'ng2-webstorage': { main: './index.js', defaultExtension: 'js' } }

Once I did this then I was able to import into app.module via import { Ng2Webstorage } from 'ng2-webstorage';

I definitely appreciate the support this library is gaining and I want to open the door to using this library even more to those users who are inexperienced like I am.

My question is...

Should I have already known to do this with systemjs (again I am still learning) or should there be a section in the README that can include this tidbit in order to help users who may be experiencing the same issue as me? Or is there a different way that I should be leveraging systemjs with this awesome library?

Thanks again for support you have shown others!

Cannot read property 'store' of undefined

Hi,

I'm getting an error of TypeError: Cannot read property 'store' of undefined

I'm pretty sure im importing and configuring it right, but here's a sample of my code:

app.module: import {Ng2Webstorage} from 'ng2-webstorage'; browser module, etc

and then in my service:
`import {LocalStorageService} from 'ng2-webstorage';
@Injectable()
export class LoginService {

constructor (private http: Http,  private storage:LocalStorageService) {}
private saveTokenId(res: Response) {
    let body = res.json();
    let success: boolean;
    try {
        this.storage.store('userId', 'value');
        success = true;
    } catch(e){
        console.log(e)
        success = false;
    } finally {
        return success
    }
}`

Custom Prefix Separator

Hi Friends. We should let users customize the Prefix Separator. For example in angular-local-storage (angular1) the default prefix is "ls" and the separator is "." so if you create a value look like "ls.YOUR_VALUE". Here your separator is "|" and yhis value should be a variable.

In keyStorage.js i change
return CUSTOM_LIB_KEY + "|" + raw.toString().toLowerCase();
By
return CUSTOM_LIB_KEY + "." + raw.toString().toLowerCase();

and works perfect but a new update will broke this.

BrowserModule already imported

I have tried using this module in my application, and i get the above error message.

I believe your supposed to import the CommonModule instead of the BrowserModule in your code?

Inject services in others

Is it possibile to use the LocalStorageService and SessionStorageService in my custom service?

I would like to create a wrapper for this services with some custom configuration but I can't inject them in my custom service. I think they are missing the @Injectable() decorator, right?

Is this module supposed to be compiled before inclusion?

Pardon me if I've overlooked something fundamental to Angular2 as the module inclusion has given me more trouble than anything thus far. Anyhow, I see the entire source code for the repo is in TypeScript. Given that Angular imports script files in the browser using XHR, do they not ultimately need to be basic JavaScript files?

If the library is intended to be compiled with tsc, I am receiving the following errors when attempting to do so:

node_modules/ng2-webstorage/lib/app.ts(5,1): error TS2308: Module './decorators' has already exported a member named 'WebStorage'. Consider explicitly re-exporting to resolve the ambiguity. node_modules/ng2-webstorage/lib/helpers/storageObserver.ts(8,45): error TS2314: Generic type 'EventEmitter<T>' requires 1 type argument(s). node_modules/ng2-webstorage/lib/interfaces/storage.ts(8,23): error TS2314: Generic type 'EventEmitter<T>' requires 1 type argument(s). node_modules/ng2-webstorage/lib/services/webStorage.ts(29,29): error TS2314: Generic type 'EventEmitter<T>' requires 1 type argument(s).

Angular 4.0.0

Will ng2-webstorage be updated to use new Angular 4.0.0?

Or maybe will be new ng4-webstorage library?

Final version was released today

Custom configuration is ignored when decorators are used

Version: [email protected]

I have configured ngx-webstorage to use a custom prefix and separator.
Ng2Webstorage.forRoot({ prefix: 'my_custom', separator: '.', caseSensitive: true }),

  1. When I use the decorator like this:
    @LocalStorage('test') private i:string;
    Actual result:
    ng2-webstorage|test = null
    Expected result:
    my_custom.test = null

  2. When I use the decorator like this:
    @LocalStorage('test', 'hello') private i:string;
    Actual result:
    ng2-webstorage|test = 'hello'
    Expected result:
    my_custom.test = 'hello'

  3. When I use the decorator like this:
    @LocalStorage('test') private i:string = 'hello;
    Actual result:
    ng2-webstorage|test = null my_custom.test = 'hello'
    Expected result:
    my_custom.test = 'hello'

localStorage.observe not worked for changes in other window

In window 1 I use

 this.storage.observe('boundValue')
    .subscribe((newValue) => {
      console.log(newValue);
    })

In window 2 I set new value this.storage.store('boundValue', 'new value') and I have nothing.
Will be good to observe changes from other windows.

Synchronization issue

Hello,

When using the decorators, It appears that the synchronization to the session storage and local storage does not happen properly. See below :

import { LocalStorage, SessionStorage} from 'ng2-webstorage';
@Component({
    selector: 'game', 
    templateUrl: 'game.component.html',
    styleUrls: ['game.component.css']
})
export class GameComponent 
{ 
    @LocalStorage("default") private test: number;
     constructor(  ) {
        this.test = 1234;    // Local storage is set to 1234
        //  ....
        // other code
        //  ...

        this.test = 5678;  // Local storage remains at 1234
  }
}

How to Support Server Rendering with ngx-webstorage

Doing an online shop project. Decorate cartline array with @localStorage(). The shopping cart works perfectly on the client side. But it failed (cannot continue loading the website) when I tried server rendering. So is it possible to get the item count when the app is loaded first from the server?

TypeError: Cannot read property 'local' of undefined

when bundling ngx-webstorage version 1.8.0 with webpack & aot plugin for production, the minified script crash at runtime at this line:
o=(n.n(i),"ng2-webstorage"),s="|",a=!1,l=(r={},r[i.STORAGE.local]="local",r[i.STORAGE.session]="session",r)
storage-problem
storage-error

At development it all works normally. This is the non minified vendor script:
webstorage_nonminified

So the minified version has a problem with the STORAGE enum.
Any thoughts about this?
Thanks

SyntaxError in constants/lib.js

Hi!

I am trying to include this service into an Ionic 2 RC.0 app and when bundleing the app this error occurs:

[14:25:17]  bundle dev started ...
[14:25:22]  SyntaxError: Unexpected token (9:6) in C:\Daten\Entwicklung\e-netz\PROMT-UI_V2\node_modules\ng2-webstorage\dist\constants\lib.js
    at Parser.pp$4.raise (C:\Daten\Entwicklung\e-netz\PROMT-UI_V2\node_modules\rollup\dist\rollup.js:4072:13)
    at Parser.pp.unexpected (C:\Daten\Entwicklung\e-netz\PROMT-UI_V2\node_modules\rollup\dist\rollup.js:2270:8)
    at Parser.pp.semicolon (C:\Daten\Entwicklung\e-netz\PROMT-UI_V2\node_modules\rollup\dist\rollup.js:2247:59)
    at Parser.pp$1.parseVarStatement (C:\Daten\Entwicklung\e-netz\PROMT-UI_V2\node_modules\rollup\dist\rollup.js:2614:8)
    at Parser.pp$1.parseStatement (C:\Daten\Entwicklung\e-netz\PROMT-UI_V2\node_modules\rollup\dist\rollup.js:2398:17)
    at Parser.pp$1.parseTopLevel (C:\Daten\Entwicklung\e-netz\PROMT-UI_V2\node_modules\rollup\dist\rollup.js:2315:23)
    at Parser.parse (C:\Daten\Entwicklung\e-netz\PROMT-UI_V2\node_modules\rollup\dist\rollup.js:2182:15)
    at parse (C:\Daten\Entwicklung\e-netz\PROMT-UI_V2\node_modules\rollup\dist\rollup.js:4972:37)
    at tryParse (C:\Daten\Entwicklung\e-netz\PROMT-UI_V2\node_modules\rollup\dist\rollup.js:7312:10)
    at new Module (C:\Daten\Entwicklung\e-netz\PROMT-UI_V2\node_modules\rollup\dist\rollup.js:7346:20)

I am working on Windows 10. Looking at that file in an editor does not seem to show any cause of this. Do you have an idea how to overcome this?

Angular 2.0.0-rc.4

Your library is great but now a bit outdated.
Please update Angular version to 2.0.0-rc.4

Ng2Webstorage possibly causes error on angular i18n module

I just configured the built-in Angular i18n service to my project that uses Ng2Webstorage.

On calling "ng-xi18n", the following error occurs:

Error: Unexpected value 'Ng2Webstorage' imported by the module 'AppModule'
    at C:\Users\XYZ\node_modules\@angular\compiler\bundles\compiler.umd.js:14126:37
    at Array.forEach (native)
    at CompileMetadataResolver.getNgModuleMetadata (C:\XYZ\node_modules\@angular\compiler\bundles\compiler.umd.js:1411
1:46)
    at C:\Users\XYZ\node_modules\@angular\compiler\bundles\compiler.umd.js:12952:58
    at Array.forEach (native)
    at OfflineCompiler.analyzeModules (C:\XYZ\node_modules\@angular\compiler\bundles\compiler.umd.js:12951:21)
    at Extractor.extract (C:\XYZ\node_modules\@angular\compiler-cli\src\extract_i18n.js:92:47)
    at extract (C:\XYZ\node_modules\@angular\compiler-cli\src\extract_i18n.js:16:35)
    at Object.main (C:\XYZ\node_modules\@angular\tsc-wrapped\src\main.js:30:16)
    at Object.<anonymous> (C:\XYZ\node_modules\@angular\compiler-cli\src\extract_i18n.js:160:9)
Extraction failed

Maybe it just a configuration mistake that I have done, but perhaps it is possible to add *.metadata.json files to fix the problem.

Can anyone evaluate this?

Store JSON objects with serializer/deserializer

Maybe I missed it in documentation, but it appears theres no way to store and retrieve JSON objects, just literals. If its not already implemented all you would need to do is add a wrapper for JSON.stringify(json) for serializing and JSON.parse(json) for deserializing. As for now, I am just able to store singe values

Localstorage/sessionstorage clear not working

As title describes, the clear function on both LocalStorageService and SessionStorageService do not seem to work. I have tried the following for each:

this.storage.clear('myprop');
this.storage.clear();

Ionic 2 importing not working

Hello, I'm currently developing an Ionic 2 app.
I installed the package through npm and added to my app.module.ts, but when I try to use it in my service I get an error:
error

Customizing key prefix?

Hello!

Thank you for this great module!

However, is it possible to customize prefix used for storage keys? It's ng2-webstorage| by default.

Thanks!

1.5.0 won't work with latest angular-cli 1.0.0-beta.25.5

If I update to 1.5.0 I'm getting this on my console:

bootstrap bbae97d…:135Uncaught TypeError: Cannot convert undefined or null to object
    at hasOwnProperty (<anonymous>)
    at Function.__webpack_require__.o (bootstrap bbae97d…:135)
    at Object.<anonymous> (vendor.bundle.js:42314)
    at __webpack_require__ (bootstrap bbae97d…:52)
    at Object.206 (index.ts:2)
    at __webpack_require__ (bootstrap bbae97d…:52)
    at Object.758 (auth.routing.ts:9)
    at __webpack_require__ (bootstrap bbae97d…:52)
    at Object.205 (shared.module.ts:47)
    at __webpack_require__ (bootstrap bbae97d…:52)
    at Object.760 (authentication.guard.ts:10)
    at __webpack_require__ (bootstrap bbae97d…:52)
    at Object.753 (about.routing.ts:10)
    at __webpack_require__ (bootstrap bbae97d…:52)
    at Object.755 (app.component.ts:9)
__webpack_require__.o @ bootstrap bbae97d…:135
(anonymous) @ vendor.bundle.js:42314
__webpack_require__ @ bootstrap bbae97d…:52
206 @ index.ts:2
__webpack_require__ @ bootstrap bbae97d…:52
758 @ auth.routing.ts:9
__webpack_require__ @ bootstrap bbae97d…:52
205 @ shared.module.ts:47
__webpack_require__ @ bootstrap bbae97d…:52
760 @ authentication.guard.ts:10
__webpack_require__ @ bootstrap bbae97d…:52
753 @ about.routing.ts:10
__webpack_require__ @ bootstrap bbae97d…:52
755 @ app.component.ts:9
__webpack_require__ @ bootstrap bbae97d…:52
592 @ src async:7
__webpack_require__ @ bootstrap bbae97d…:52
1259 @ .*$:7
__webpack_require__ @ bootstrap bbae97d…:52
webpackJsonpCallback @ bootstrap bbae97d…:23
(anonymous) @ main.bundle.js:1

And error goes away if I downgrade to 1.4.3

Minor naming glitches in npm

The npm project for ngx-webstorage says in the install instructions:

Download the library using npm npm install --save ng2-webstorage

That should presumably now change to say ngx-webstorage if that is to be the name going forward. Or give both options and explain the difference if you have to have the same text on both.

Also, while I think they're now the same module, npm search still returns jbeck8176... as the author of ngx-webstorage:

# npm search ng2-webstorage
NAME                      | DESCRIPTION          | AUTHOR          | DATE       | VERSION  | KEYWORDS
ng2-webstorage            | angular2 webstorage… | =polochon       | 2017-04-21 | 1.8.0    | typescript angular2 ng2 localstorage sessionStorage
ngx-webstorage            | angular2 webstorage… | =jbeck8176…     | 2017-04-21 | 1.8.0    | typescript angular2 ng2 localstorage sessionStorage

LocalStorage Observable Error: 'Decorators are not valid here.'

Loving the package so far! Having just a small issue with the LocalStorage decorator.

Attempting to put @LocalStorage('value') within the class (or outside of it) will cause an error.

I looked further into the issue, and saw #microsoft/TypeScript#8257, so it could possibly be just an issue with typescript compilation?

(feel free to close out the thread if not a valid issue)

Handle StorageEvent "clear" events properly

I'm running into an issue where the library doesn't seem to handle storage "clear" events (e.g., sessionStorage.clear()). It runs into in exception in KeyStorageHelper.isManagedKey since the key for clear events is always null, as described by MDN (I'm crossing my fingers that MDN matches the spec here).

Additionally, the clear event doesn't seem to be clearing the module cache or emitting events for the cleared values.

image

Error encountered resolving symbol values statically

I am using [email protected]. My purpose is to do AOT compilation with ngc, but I receive this error from ngc:

Error: Error encountered resolving symbol values statically. Calling function 'Ng2Webstorage', function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol AppModule in /Users/carlos/Documents/Workspaces/Angular Workspace/myapp/src/app/app.module.ts.

The code of AppModule is:

import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';

import {Ng2Webstorage} from 'ng2-webstorage';

...

@NgModule({
    imports: [BrowserModule, Ng2Webstorage.forRoot({prefix: 'MYAPP', separator: '_'}), ...],
    declarations: [...],
    bootstrap: [...]
})
export class AppModule { }

I think your library is prepared for AOT and I am initialising correctly in my AppModule. Do you have any clue about what can be failing?

local storage - deleting a key only impacts the current tab in the browser

Hi,

see #23

The deletion of a key only impacts the current tab and all other tabs will retrieve the key from the javascript cache object which is not updated. (maybe it works as designed :-))

The problem I'm facing is when storing sensitive data which should be deleted (is logged in?) but still remains until the page is refreshed.

I've created my first little example with plnkr - hopefully with no errors:

http://plnkr.co/edit/S9nWN60fpS6TLUEbWf5L?p=preview&open=app%2Fapp.component.ts

  • Open the link and click on "Set Key in local storage"
  • Open a second tab. You'll se that the key is already setted
  • Click "Delete key from local storage" in one tab
  • Go to the other tab and click set key in local storage - you'll get the alert that the key is retrieved from the storage

Thanks in advance!
Marc

JSON.parse(value) when retrieve ?

is it possible to define custom transformation each time we retrieve a value ? I store a hole JSON object as a value and I need to parse it each time I retrieve or bind to attribute using a decorator ?

Warning message while starting node server

I'm getting this warning massage in my server console. can you please help me to resolve it?

Cannot find SourceMap 'data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29yZS51bWQuanMiLCJzb3VyY2VzIjpbIi4uL2Rpc3QvZW51bXMvc3RvcmFnZS5qcyIsIi4uL2Rpc3QvY29uc3RhbnRzL2xpYi5qcyIsIi4uL2Rpc3QvaGVscGVycy9rZXlTdG9yYWdlLmpzIiwiLi4vZGlzdC9oZWxwZXJzL3N0b3JhZ2VPYnNlcnZlci5qcyIsIi4uL2Rpc3QvaGVscGVycy9tb2NrU3RvcmFnZS5qcyIsIi4uL2Rpc3QvaGVscGVycy93ZWJTdG9yYWdlLmpzIiwiLi4vZGlzdC9zZXJ2aWNlcy93ZWJTdG9yYWdlLmpzIiwiLi4vZGlzdC9zZXJ2aWNlcy9sb2NhbFN0b3JhZ2UuanMi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DLEFBQ0wsOzs7Ozs7Ozs7LDs7LDs7In0= in \node_modules\ng2-webstorage\bundles

Hardcoded window global

Currently window global is hardcoded here. The check doesn't make much sense since this will throw type error in Node any way if global.window wasn't stubbed.

Probably should be

if (typeof window !== 'undefined') {

Serialization Doesn't Work For Objects

I've seen you say in a lot of other issues that this library should work for objects. In my experience it doesn't. Here's some code that demonstrates the point:

test.component.ts:

import { Component, OnInit } from '@angular/core';

import { SessionStorage } from 'ng2-webstorage';

class MyClass {
  var: string;
}

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

  @SessionStorage()
  myObj: MyClass;
  @SessionStorage()
  direct: string;

  constructor() { }

  ngOnInit() {
    if (!this.myObj)
      this.myObj = new MyClass();
  }

}

test.component.html

<input [(ngModel)]="myObj.var">
<br>
<input [(ngModel)]="direct">

After testing the page, you can see my screenshot along with looking at the session local variables in Chrome. Notice that the object is not serialized properly. We do not get its member. The direct string does work.
screenshot from 2017-01-25 20-41-16

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.