Giter VIP home page Giter VIP logo

angular-async-local-storage's Introduction

Hi there πŸ‘‹

angular-async-local-storage's People

Contributors

cyrilletuzi avatar dependabot[bot] 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

angular-async-local-storage's Issues

ERROR Error: IndexedDB setter issue : Key already exists in the object store..

Hello,
I have this error ;(

core.js:1440 ERROR Error: IndexedDB setter issue : Key already exists in the object store..
at MergeMapSubscriber.eval [as project] (angular-async-local-storage.es5.js:303)
at MergeMapSubscriber._tryNext (mergeMap.js:128)
at MergeMapSubscriber._next (mergeMap.js:118)
at MergeMapSubscriber.Subscriber.next (Subscriber.js:92)
at IDBRequest.handler (FromEventObservable.js:212)
at ZoneDelegate.invokeTask (zone.js:421)
at Object.onInvokeTask (core.js:4724)
at ZoneDelegate.invokeTask (zone.js:420)
at Zone.runTask (zone.js:188)
at ZoneTask.invokeTask [as invoke] (zone.js:496)

Feature: better JSON schema interface

Last additions to TypeScript should allow a better interface for JSONSchema (allowing properties which are specific to a type to only be allowed where they are allowed).

Validation Documentation notes @ngw-pwa, my code shows @ngx-pwa

In the Validation documentation regarding the use of JSON schema's, all the imports are from '@ngw-pwa/local-storage', while my project imports from '@ngx-pwa/local-storage', @ngw redlines in VSCode.

Is the documentation incorrect, or do I have an issue with my library?

Extension settings

Hello, good library!
I would like to be able to select the storage.
Could you add in LocalStorageProvidersConfig and consider this option in localDatabaseFactory.
If you do not make it difficult to do it yourself or i can do it pull request ?

Return Observable of getItem()

Hello I wrap AsyncLocalStorage into another service.

@Injectable()
export class MyService {

    constructor(protected _localStorage: AsyncLocalStorage) { }

    public getUser() {
        return this._localStorage.getItem<User>('user');
    }

    public setUser(user: User) {
        this._localStorage.setItem('user', user)
            .subscribe(() => { },
            error => console.log);
    }
}

Inject service in the component and subscribe to method getUser which use getItem method..

export class AppComponent implements OnInit{

constructor(private _myService: MyService){
}

ngOnInit(): void {
    this._myService.getUser().subscribe(user=>console.log(user))
}

}

getUser produce only one value null when I add new user to via setUser method to local storage in the AppComponent subscribe doesn’t produce value but when I subscribe directly to _localStorage.getItem()
it works.

I use Angular 5 and Typescript 2.4.2.

Feature: unknown type for getItem calls without a validation

The issue

Any local storage (localStorage, indexedDb...) is not secure by nature, as the client can forge the value (intentionally or not). It can cause security issues and errors (as the received data type may not be what you expected). Then, any data coming from local storage should be checked before used.

That's why v5 of this lib introduced a new option for getItem() to validate the data against a JSON schema. But for now it's optional (to not break with previous versions and to let users use their own validation system), which is bad.

The proposition

The proposition is to require a validation. It is know possible with the new type unknown in TypeScript >= 3, supported by Angular >= 7.

It would mean:

  • no change for users already doing a validation via the JSON schema option of the lib:
// Before and after v7.0.0-beta.1
this.localStorage.getItem<string>('test', { schema: { type: 'string' } }).subscribe((result) => {
  result; // type: string
  result.substr(0, 2); // OK
});
  • getItem() calls with no schema option would now return unknown (instead of any), forcing users to validate the data. For example:
// Before v7.0.0-beta.1
this.localStorage.getItem('test').subscribe((result) => {
  result; // type: any
  result.substr(0, 2); // Bad but compilation OK
});

// With v7.0.0-beta.1
this.localStorage.getItem('test').subscribe((result) => {

  result; // type: unknown
  result.substr(0, 2); // Compilation error

  if (typeof result === 'string') {
    result; // type: string
    result.substr(0, 2); // OK
  }

});

Pros:

  • Good for security!
  • Good for avoiding errors (which are not tolerable in an app)!

Cons:

  • As it would be managed on the TypeScript level, I don't see a way to provide a runtime option to keep the old behavior, so it would be an important breaking change. But the new errors that would be raised would be very legitimate, as they mean something was done the wrong way before.

You can test with: npm install @ngx-pwa/local-storage@beta

Feedback welcome!

has no exported member 'LocalStorageModule' @5.30

I've ran yarn add @ngx-pwa/local-storage@5 and it's installed 5.3.0

I've added in app.module.ts

import { LocalStorageModule } from '@ngx-pwa/local-storage';

and adding LocalStorageModule to my @NgModule

But get the dreaded

has no exported member 'LocalStorageModule'

I've tried without the import line but I get an error in my front end

core.js:1449 ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[CreateComponent -> LocalStorage]:

Import service that don't need to define in constructors

I have an issue when I extends one class and call value in constructors :
Ex: export class TestStore extends CommonStore<TestState> { constructor() { super('test', init) } }
And class CommonStore I want call service localStorage in your library.
export abstract class CommonStore<S> protected constructor(private key: string, init?: S) { super( // How to I able to use function localStorage that don't need inject into constructors? // Type of I able to import and call it. ) }
Please help me .
Thanks

session storage

Would it be possible to add a sessionStorage database? Or a way to configure the localStorage db to use sessionStorage? API is pretty much the same I thought.

Get data in sync

Is there a way to get the data synchronized rather than async? sometimes you want is to be in sync.

thanks

Error retrieving and setting data in different structure

Hey,

Well, I wanted to share indexedDB data between two different apps. One is in angular but the other is not. My solution was to use LocalForage, given you based your work on it.

But saving a JS object with LocalForage and then using or updating it with this library didn't work, even though the database and table were the same. After some analysis, I noticed the cause to be that you wrap the object in a value property.

Whether you want your library to be compatible with LocalForage is another discussion, but I guess you may want to handle the errors more precisely.

Setup

Save a JS object, but don't wrap it in another object with the value property. Then make LocalStorage get or update this object.

Current behavior

getItem observable returns null.
setItem observable returns the error (I even thought it was related to #47):

IndexedDB setter issue : Key already exists in the object store.

More precise behavior

getItem observable throws an error or actually reads the current value.
setItem observable returns a more descriptive error or normalizes the structure to what it should be.

IndexedDB setter issue : Key already exists in the object store..

IndexedDB setter issue : Key already exists in the object store..

first removing a item then iam adding item into local storage event hough it shows this error
i used this code

this.localStorage.removeItem('selectedItem').subscribe(() => {
this.localStorage.setItem('selectedItem', item).subscribe(() => { });
}, (error) => {
this.localStorage.setItem('selectedItem', item).subscribe(() => { });
});

Array of Object Validation

I don't quite understand if I validate json correct. As I am getting this error ERROR Error: JSON invalid

The data looks the next:

[
    {
      "id": "1",
      "name": "Customer #1",
      "avatar": "avatar.png",
      "phone": "+312456791",
      "email": "[email protected]",
      "address": "Address 1",
      "birthday": "1993-12-17",
      "gender": "female"
    }
  ],

Here is the schema I use:

schema: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            id: { type: 'string'} as JSONSchemaString,
            name: { type: 'string' } as JSONSchemaString,
            phone: { type: 'string' } as JSONSchemaString,
            avatar: { type: 'string' } as JSONSchemaString,
            address: { type: 'string' } as JSONSchemaString,
            birthday: { type: 'string' } as JSONSchemaString,
            gender: { type: 'string' } as JSONSchemaString
          }
        }
      }

I've saved to indexedDb array of customers - heare a screenshot of my db http://joxi.ru/l2ZYykdsw1KxOm

Thanks for your reply.

GetItem problem

Hi, I have a problem with getItem.
When I request getItem ("products") (which is already set) and place a console.log (), it returns the array with the 3 products, but when it is passed by filter it returns null.

this.localStorage.getItem("products").subscribe(products => { let temp = products;
console.log(temp); // [{id:312313,...}, {....}, ....] if (temp) { //null
return temp.filter(x => x.Destacado == true); }
});

Multiple stores?

Hi,

might it be possible to have multiple stores? Like I have the scenario where I save flags and settings of the app (which you'd normally put in localStorage). But then I also have some app data which I regularly sync. For that 2nd scenario, I simply do a wipe & resync when I need to refresh the data, but obviously I'd only like to .clear() the app data, not the user's settings and flags.
Ofc, what I could do is to use a single "key" and store an array of app data inside there, but since it's a lot of data (PDF documents in binary form), I wouldn't want to serialize/deserialize it continuously from memory.

With the current implementation this isn't possible I guess, right? Any interest/idea on adding this feature? Would also be willing to help in case.

ng build failed

src/app/app.module.ts(9,10): error TS2305: Module '"/home/kenneth/Projects/coinotc-wallet-api/wallet-mgmt-web/node_modules/@ngx-pwa/local-storage/local-storage"' has no exported member 'LocalStorageModule'.

Version 7.1.0 uses localStorage instead of IndexedDB

After upgrading Angular and this lib to latest version: 7.1.0 (for both) it started to use localStorage instead of IndexedDB which it was using before. I'm using Chrome 70 (70.0.3538.110) and checked it as well on Safar 12.0.1 (14606.2.104.1.1) - both on OSX 10.14.1.

My package.json looks like this:

{
"name": "myrepo",
"version": "1.0.0",
"private": true,
"dependencies": {
"@angular/animations": "^7.1.0",
"@angular/cdk": "^7.1.0",
"@angular/common": "^7.1.0",
"@angular/compiler": "^7.1.0",
"@angular/core": "^7.1.0",
"@angular/forms": "^7.1.0",
"@angular/http": "^7.1.0",
"@angular/material": "^7.1.0",
"@angular/material-moment-adapter": "^7.1.0",
"@angular/platform-browser": "^7.1.0",
"@angular/platform-browser-dynamic": "^7.1.0",
"@angular/pwa": "^0.10.6",
"@angular/router": "^7.1.0",
"@angular/service-worker": "^7.1.0",
"@ngx-pwa/local-storage": "^7.1.0",
"core-js": "^2.5.4",
"moment": "^2.22.2",
"rxjs": "^6.3.3",
"zone.js": "~0.8.26"
},
"devDependencies": {
"@angular-devkit/build-angular": "^0.10.6",
"@angular/cli": "~7.0.6",
"@angular/compiler-cli": "^7.1.0",
"@angular/language-service": "^7.1.0",
"@types/jasmine": "^3.3.0",
"@types/jasminewd2": "^2.0.6",
"@types/node": "^10.12.10",
"codelyzer": "~4.5.0",
"jasmine-core": "~3.3.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~3.1.1",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "^2.0.4",
"karma-jasmine": "~2.0.1",
"karma-jasmine-html-reporter": "^1.4.0",
"protractor": "^5.4.1",
"ts-node": "~7.0.1",
"tslint": "~5.11.0",
"typescript": "~3.1.6"
}
}

@ngx-pwa/local-storage@6 : No matching version found

npm i --save @ngx-pwa/local-storage@6

npm ERR! code ETARGET
npm ERR! notarget No matching version found for @ngx-pwa/local-storage@6
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\User\AppData\Roaming\npm-cache\_logs\2018-05-19T02_21_50_484Z-debug.log

What it says, I can't install v6 for Angular 6 as per the README. Any ideas?

Not possible to use catch / filter / or any other RxJs Observable methods after setItem(...)

Hi. How can I catch errors and transform it into Observable.of(false)?
Or how to use filter or any other Observable method from setItem('local-storage-variable', variable) observable? I want to use catch, but I try filter also and always with the same result:

Part of my code:

...
import { AsyncLocalStorage } from 'angular-async-local-storage';
import { Observable } from 'rxjs/Observable'; // I try it also from rxjs/Rx
import 'rxjs/add/operator/catch'; // I try it also without this line
...
@Injectable()
export class SessionService {
  constructor(
    private asyncLocalStorage: AsyncLocalStorage,
    ...
  ) { }
  public logout(): Observable<boolean> {
    return this.asyncLocalStorage.setItem('session', this.session)
      .filter(f => f === true) // error on this line
      .catch(err => Observable.of(false)); // error on this line if previous is commented
  }

Errors:
ERROR TypeError: this.asyncLocalStorage.setItem(...).filter is not a function
ERROR TypeError: this.asyncLocalStorage.setItem(...).catch is not a function
Versions in angular project: "angular-async-local-storage": "^2.0.0", "rxjs": "^5.4.3"

Thank you in advance very much for your help.

Is it truly async?

Reading this piece of code:

/**
* Gets an item value in local storage
* @param key The item's key
* @returns The item's value if the key exists, null otherwise, wrapped in an RxJS Observable
*/
getItem<T = any>(key: string): Observable<T | null> {
const unparsedData = this.localStorage.getItem(key);
let parsedData: T | null = null;
if (unparsedData != null) {
try {
parsedData = JSON.parse(unparsedData);
} catch (error) {
return observableThrow(new Error(`Invalid data in localStorage.`));
}
}
return observableOf(parsedData);
}

It doesn't seem to be async actually, since this line will block the returning of the observable:

const unparsedData = this.localStorage.getItem(key);

You are returning an observable of the existing response from unparsedData. If for some reason browser takes too long to give a response to LocalStorage.getItem() method, all the execution from here will be blocked until it's ready.

i use angular 4.0 typescript 2.2

ERROR in Error encountered resolving symbol values statically. Calling function
' makeDecorator', function calls are not supported. Consider replacing the funct
ion or lambda with a reference to an exported function, resolving symbol NgModul
e in D:/code/iris_angular_gitlab/node_modules/angular-async-local-storage/node_m
odules/@angular/core/core.d.ts, resolving symbol AsyncLocalStorageModule in D:/c
ode/iris_angular_gitlab/node_modules/angular-async-local-storage/src/async-local
-storage_module.d.ts, resolving symbol AsyncLocalStorageModule in D:/code/iris_a
ngular_gitlab/node_modules/angular-async-local-storage/src/async-local-storage_m
odule.d.ts

Failed to execute 'transaction' on 'IDBDatabase' on Google Chrome

Error: Uncaught (in promise): InvalidStateError: Failed to execute 'transaction' on 'IDBDatabase': The database connection is closing.
Error: Failed to execute 'transaction' on 'IDBDatabase': The database connection is closing.

Occasionally I get this error from the client through sentry and I don't know what the issue might be.
Google Chrome Version 67.0.3396.99

IndexedDB connection issue in Electron

I'm using angular + electron to whip up some app. When I try to access the items I placed in to this store, I get the error;
ERROR Error: IndexedDB connection issue.
at MergeMapSubscriber.eval [as project] (angular-async-local-storage.es5.js:301)
at MergeMapSubscriber._tryNext (mergeMap.js:128)
at MergeMapSubscriber._next (mergeMap.js:118)
at MergeMapSubscriber.Subscriber.next (Subscriber.js:91)
at IDBOpenDBRequest.handler (FromEventObservable.js:212)
at ZoneDelegate.invokeTask (zone.js:425)
at Object.onInvokeTask (core.js:4617)
at ZoneDelegate.invokeTask (zone.js:424)
at Zone.runTask (zone.js:192)
at ZoneTask.invokeTask [as invoke] (zone.js:499)

How can I work that out to get the module work because I don't know if its just because I'm using electron or not!

Thanks

Update instead of Add? – re: Error: IndexedDB setter issue : Key already exists in the object store

This is more of a question as to the correct approach to updates to data in the local store, not an issue or a bug, so my apologies if this isn't the correct venue.

I'm running into this error (correctly, I might add):

error occured setting data in the local store Error: IndexedDB setter issue : Key already exists in the object store
This occurs where I've set a key in the store, and then later am trying to reset a value for the same key, and it throws the above error. I can't anticipate when the user will navigate through a specific workflow that will cause a value to be fetched from over the network and re-added to the local store, so I'm trying to determine the best way to handle this.

My understanding is we can only add, not update(put) an object into the store, which brings me to the question of how to handle updates. Ideally I would like to update by default any existing value for a key already in the store, but failing that, is the accepted approach to always test for the presence of a key, and if it exists, to delete it first, then add the new value with that key?

not working with universal

I dont can run universal app with 'ts-node' and 'angular-async-local-storage'
source app: https://github.com/gorniv/universal/tree/material

/Users/Gorniv/GitHub/universal/UniApp/node_modules/angular-async-local-storage/src/async-local-storage.js:1
(function (exports, require, module, __filename, __dirname) { import { Injectable } from '@angular/core';
                                                              ^^^^^^

SyntaxError: Unexpected token import
    at createScript (vm.js:74:10)
    at Object.runInThisContext (vm.js:116:10)
    at Module._compile (module.js:537:28)
    at Object.Module._extensions..js (module.js:584:10)
    at Module.load (module.js:507:32)
    at tryModuleLoad (module.js:470:12)
    at Function.Module._load (module.js:462:3)
    at Module.require (module.js:517:17)
    at require (internal/module.js:11:18)
    at Object.angular-async-local-storage/src/async-local-storage (/Users/Gorniv/GitHub/universal/UniApp/dist-server/main.462f910c364768b8c046.bundle.js:4079:18)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] uad: `ng build --dev --output-hashing=all --aot=true && ng build --aot=true --output-hashing=all --dev --app 1 && ts-node server`

Support full JSON Schema validation

Only a subset of JSON Schema is used to validate the data in this lib. Just follow the provided JSONSchema interface.

In version 5 of this lib, you can only use:

  • type
  • properties and required
  • items
  • required

Since version 6 of this lib, you can use:

New types:

  • enum
  • const

Validation of numbers:

  • multipleOf
  • maximum
  • exclusiveMaximum
  • minimum
  • exclusiveMinimum

Validation of strings:

  • maxLength
  • minLength
  • pattern

Validation of arrays:

  • maxItems
  • minItems
  • uniqueItems

The following ones won't be included because the role of the validation feature in this lib is to check the data against corruption, so validation should be more strict:

  • additionalItems
  • additionalProperties
  • propertyNames
  • maxProperties
  • minProperties
  • patternProperties
  • not
  • contains
  • allOf
  • anyOf
  • oneOf
  • array for type

Support for "upgradeneeded"

Working on a fairly complex project has presented the challenge of managing database data versions. Has there been given any thought into supporting database version control through the "upgradeneeded" event. It seems to be in the library, however, used in self management rather than surfacing an interface for application usage. Right now the only option I can see is to manually store and test for versions, which introduces additional challenged around validation and upgrading, or is there a recommendation on how best to deal with data version discrepancies. Thanks.

Build failure using latest release

After installing the latest release (which fixed #47), I now get a build failure trying to build my project:

ERROR in node_modules/@ngx-pwa/local-storage/lib/lib.service.d.ts(2,31): error TS2307: Cannot find module './databases/local-database'.
node_modules/@ngx-pwa/local-storage/lib/lib.service.d.ts(3,28): error TS2307: Cannot find module './validation/json-schema'.
node_modules/@ngx-pwa/local-storage/lib/lib.service.d.ts(4,31): error TS2307: Cannot find module './validation/json-validator'.
node_modules/@ngx-pwa/local-storage/ngx-pwa-local-storage.d.ts(5,44): error TS2307: Cannot find module './lib/databases/local-database'.
node_modules/@ngx-pwa/local-storage/public_api.d.ts(1,28): error TS2307: Cannot find module './lib/validation/json-schema'.
node_modules/@ngx-pwa/local-storage/public_api.d.ts(2,31): error TS2307: Cannot find module './lib/databases/local-database'.
node_modules/@ngx-pwa/local-storage/public_api.d.ts(3,35): error TS2307: Cannot find module './lib/databases/indexeddb-database'.
node_modules/@ngx-pwa/local-storage/public_api.d.ts(4,38): error TS2307: Cannot find module './lib/databases/localstorage-database'.
node_modules/@ngx-pwa/local-storage/public_api.d.ts(5,35): error TS2307: Cannot find module './lib/databases/mock-local-database'.
node_modules/@ngx-pwa/local-storage/public_api.d.ts(6,31): error TS2307: Cannot find module './lib/validation/json-validator'.

I can avoid this error using skipLibCheck: true in my tsconfig, but this should definitely be fixed.

AOT Compiling in Angular 6 causes the LocalStorage Module to go missing

Angular 6 app. Works in dev mode. However, we were getting errors in the console when deploying our app using v6 of this component. Enabled source maps to figure out what was going on and found out that the library is missing after the application is AOT compiled.

image

When aot compiling for angular, the library goes missing.

In Dev Mode:

image

After AOT compiled.

image

I'm including our package.json and angular.json

ClientApp.zip

I can do the `removeItem` command

I need to remove the variable in the indexedDB but the command removeItem doesn't work at all(don't show any errors).

I'm using this command:

this.storage.removeItem('dateFilter').subscribe(() => {});

Support conversion to promise?

Thanks in advance for your help.

I have saved an array of stock objects successfully to storage (I looked at the IndexedDB and Chrome). I am unable to pull them back out as a promise. It returns a promise but does not resolve.

let result: Promise<Stock[]> = this._storage.getItem('Stocks').toPromise();

IndexedDB restricted in cross-origin iframes in Safari

Hey there
We get errors about IndexedDB in Safari as well as Mobile Safari but only when using iFrames.

SecurityError: IDBFactory.open() called in an invalid security context

Is it possible to use localStorage for such use cases as fallback.
In our implementation its used like this:

  constructor(
    protected storage: LocalStorage,
  ) 

  private updateLocalStorage(lsName: string, lsValue: any) {
    this.storage.removeItem(lsName)
      .subscribe(
        () => {
          this.storage.setItem(lsName, lsValue)
            .subscribe( () => {}, () => {} );
        },
        () => {}
      );
  }

Thanks in Advance

Feature Request: Get all items and search local storage

Can you add a way to get all items, so that we can search local storage?

Get all items could be along the lines of.....
let indexedDB = window.indexedDB
let open = indexedDB.open("ngStorage");
let _self = this;
open.onsuccess = function() {
let db = open.result;
let tx = db.transaction("localStorage", "readwrite");
let store = tx.objectStore("localStorage");
let pbjects= [];
store.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
objects.push(cursor.value);
cursor.continue();
}
else {
console.log(objects);
}
};

    }        

The above has been adapted from my code (which works)

Once this is in place, it would be possible for us to then filter the array of objects how we want. Right now the only way to get an item is with the key, which makes a search of the store impossible. If you have a better or more efficient way to retrieve all the items from store and search them then even better.

Issue with v7 & TypeScript 3.2 for array or object validation

In v7 of the lib, due to this regression in TypeScript 3.2, there is a problem with JSON schemas for objects or array validation if you use the generic JSONSchema interface:

const schema: JSONSchema = {
  type: 'object',
  properties: {
    firstName: { type: 'string' },
    lastName: { type: 'string' },
    age: { type: 'number' }
  },
  required: ['firstName', 'lastName']
};

or if you put a schema for an object or array directly in the method options:

this.localStorage.getItem<User>('user', { schema: {
  type: 'object',
  properties: {
    firstName: { type: 'string' },
    lastName: { type: 'string' },
    age: { type: 'number' }
  },
  required: ['firstName', 'lastName']
} });

Other schemas (string, numeric, boolean) are not affected.

Despite it's a regression, TypeScript team visibly doesn't plan to fix this until TypeScript 3.4 (yes, you've heard right...). So it has been decided to not support TypeScript 3.2.

If you're still on Angular 7.0 or 7.1 (so with TypeScript 3.1), there will be no problem with compilation. But as VS Code already uses TypeScript 3.2, errors can appear inside the editor.

If you upgraded to Angular 7.2, stick to TypeScript 3.1. Angular 7.2 still supports TS 3.1, and TS 3.2 adds nothing very interesting (except issues), so there is no need to rush the update. If you upgrade your Angular app via ng update, the CLI may update to TS 3.2, so revert this with this command:

npm install [email protected] -D

TS 3.2 issue can be bypassed by casting each JSON schema and subschemas, but we do not recommend this option as it requires a lot of work, that may need to be reverted in v8 of this lib.

Version 8 of the lib will fix these TS problems once and for all (already ready in #74). But as it will imply some breaking changes, I have to wait for v8.

Another solution is to go back to v6 of the lib, which supports Angular 7 with TypeScript 3.1 and TypeScript 3.2:

npm install @ngx-pwa/local-storage@6

Sorry for this issue, but it's beyond my control and TS team doesn't care.

Change event?

Is there a way to make the observable of getItem() listen, if a local storage item has changed? E.g. after setItem().

Feature: Map-like API to allow advanced queries in local storage

This issue tracks the project of a full query API.

Design

The API with all methods needs to be designed. It would be better to be inspired by an existing implementation (dexis.js seems to be the reference for indexedDb).

Already requested:

  • deleting specific items (#39)
  • search items (#45)

Please comment with all methods that would be useful in your projects.

Warning: each method should also work when in localStorage fallback scenarios, and performance should be checked in this case.

Implementation

As we're going towards a full RxJS adaptation of indexedDb, it would be better to be done in a framework agnostic new lib, which would be used by this one.

Maybe it already exists?

have data in LS, but subscribe is null.

Local Storage has item 'cart'

 // SERVICE
import { LocalStorage } from '@ngx-pwa/local-storage';
constructor(protected LS: LocalStorage ) {}
	public getItems(): Observable<Product[]> {
		return this.LS.getItem('cart');
	}
// MODULE
import { LocalStorage } from '@ngx-pwa/local-storage';
  constructor(protected LS: LocalStorage, private CS: CartService) {
    console.log(localStorage.getItem('cart'));
    this.LS.getItem<Product>('cart').subscribe(r => {
      console.log(r);
    });
    this.CS.getItems().subscribe(r => {
      this.shoppingCartItems = r;
      console.log(r);
    });
  }

localstorage.getItem('cart') returns data
Module Subscribe Returns Null

Feature Request: support for ng-add

 ng add @ngx-pwa/local-storage@7

Installing packages for tooling via npm.
+ @ngx-pwa/[email protected]
added 1 package from 1 contributor and audited 40277 packages in 8.423s
found 0 vulnerabilities

Installed packages for tooling via npm.
The package that you are trying to add does not support schematics. You can try using a different version of the package or contact the package author to add ng-add support.

Can't use `AsyncLocalStorage.getItem` with `.concat`

Hi, I'm trying to implement a system that manages an in-memory cache, backed by IndexedDB, populated by resources on a CDN. I want to return an observable that contains the data, as follows:

  • if the data is in the in-memory cache, return it in an Observable
  • else if the data is in IndexedDb, return read Observable
  • else return http.get Observable (and write to IDB/cache)

It seems I should be able to combine the IndexedDB read call and the http.get request via concat, and return the first non-null response, implemented roughly as follows (this is simplified, and subscribed elsewhere):

get(path): Observable<any> {
    const data = this._cache[path];
    const uri = this.getCdnPath(path);

    // storageService.read wraps AsyncLocalStorage.getItem
    const readFromStorage$ = this.storageService.read(path);

    // Angular HttpClient
    const httpGet$ = this.http.get(uri); 

    return (data) 
        ? of(data) 
        : concat(readFromStorage$, httpGet$).pipe(first(result => result));
}

This doesn't proceed past the storageService.read call. I suspect that getFile isn't returning complete, so the http.get call is abandoned (from RxJs documentation for concat):

Note that if some input Observable never completes, concat will also never complete and Observables following the one that did not complete will never be subscribed.

If I reverse the order inside .concat, both calls do proceed as expected.

NOTE: I tried to set up a plunker for this but was getting import errors.

Private browsing issue in Firefox

Follow up of comments in #20

IndexedDB is disabled in private (Firefox, Edge). Same as pouchdb/pouchdb#5641

Same goes for localStorage.

The lib should detect these cases and fallback to in-memory database.

Note it just has to avoid errors, local storage is useful for apps, where being in private browsing makes no sense.

Help is welcome for up to date information about browser support of IndexedDB and localStorage in private mode, and also for examples of detection for each case. Some seem trivial (like Edge), but some others seem quite difficult and may not be fixable (like Firefox).

Library and Demo not working in Edge or IE11

The demo works correctly in Chrome. Get the following error in Edge/IE11
File: localhost:3000
ERROR Error: IndexedDB connection issue.
"ERROR"
{
[functions]: ,
proto: { },
description: "IndexedDB connection issue.",
message: "IndexedDB connection issue.",
name: "Error",
stack: "Error: IndexedDB connection issue.
at SafeSubscriber.prototype.error (eval code:207:17)
at Subscriber.prototype._error (eval code:128:9)
at Subscriber.prototype.error (eval code:102:13)
at Subscriber.prototype._error (eval code:128:9)
at Subscriber.prototype.error (eval code:102:13)
at OuterSubscriber.prototype.notifyError (eval code:22:9)
at InnerSubscriber.prototype._error (eval code:26:9)
at Subscriber.prototype.error (eval code:102:13)
at OuterSubscriber.prototype.notifyError (eval code:22:9)
at InnerSubscriber.prototype._error (eval code:26:9)"
}
image

Moment saving

I Know, I shall save Date type to "local storage", but i want to warn you about exception.
And thanks for very useful library!

selection_212

Optional properties in an object are still validated

If I try to validate an object like the example in the documentation. I get a JSON invalid error.

interface User {
  firstName: string;
  lastName: string;
  age?: number;
}

const schema: JSONSchemaObject = {
  properties: {
    firstName: { type: 'string' } as JSONSchemaString,
    lastName: { type: 'string' } as JSONSchemaString,
    age: { type: 'number' } as JSONSchemaNumeric
  },
  required: ['firstName', 'lastName']
};

const user: User = { firstName: 'Foo', lastName: 'Bar };
this.localStorage.setItem('user', user).subscribe(() => {});

this.localStorage.getItem<User>('user', { schema }).subscribe(res => console.log(res));

image

Am I doing something wrong?

Tested with 7.2.0

Add option to specify a name for IndexedDB store

There's a high probability of running multiple apps in the same browser using this storage library, and if they all share the same default name 'ngStorage', each app has the potential to be writing over data from other apps.

It would be extremely useful to be able to specify a store name, perhaps by using something like:

    LocalStorageModule.withConfig({
      name: 'ngAppOneStore'
    }),

In the app.module?

Error with localStorage.setItem IE11

Hello, sorry for disturbing you,

Firtsly, thanks for this API.

I work on an Angular 5 project with the following version of this API : "angular-async-local-storage": "^3.1.1".

I am putting a Json object in the local storage :

this.localStorage.setItem("key", localStorageTokenInfo)

In chrome, there is no problem, but on IE11, i have the following error :

"indexedDb setter issue : undefined"

In the https://www.npmjs.com/package/angular-async-local-storage page, it is indicated that IE10+ is compatible with this API and IndexDb.

Can you help me please ?

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.