当前位置: 首页 > 软件库 > Web应用开发 > Web框架 >

angular-async-local-storage

授权协议 MIT License
开发语言 JavaScript
所属分类 Web应用开发、 Web框架
软件类型 开源软件
地区 不详
投 递 者 能旭
操作系统 跨平台
开源组织
适用人群 未知
 软件概览

Async local storage for Angular

Efficient client-side storage module for Angular:

  • simplicity: simple API like native localStorage,
  • perfomance: internally stored via the asynchronous indexedDB API,
  • Angular-like: wrapped in RxJS Observables,
  • security: validate data with a JSON Schema,
  • compatibility: works around some browsers issues and heavily tested via GitHub Actions,
  • documentation: API fully explained, and a changelog!

Sponsorship

You like this library downloaded more than 15 000 times each weekon npm?You like the serious open source work(full documentation, lib ready on day one of Angular major updates,...)?And your company is using it in projects generating money?

Well, on my side, it's a lot of unpaid work. So please consider:

By the same author

Why this module?

For now, Angular does not provide a client-side storage module, and almost every app needs some client-side storage.There are 2 native JavaScript APIs available:

The localStorage API is simple to use but synchronous, so if you use it too often,your app will soon begin to freeze.

The indexedDB API is asynchronous and efficient, but it's a mess to use:you'll soon be caught by the callback hell, as it does not support Promises yet.

Mozilla has done a very great job with the localForage library:a simple API based on native localStorage,but internally stored via the asynchronous indexedDB for performance.But it's built in ES5 old school way and then it's a mess to include into Angular.

This module is based on the same idea as localForage, but built in ES6+and additionally wrapped into RxJS Observablesto be homogeneous with other Angular modules.

Getting started

Install the package, according to your Angular version:

# For Angular LTS (Angular >= 10):
ng add @ngx-pwa/local-storage

Done!

You should stick to these commands. If for any reason ng add does not work,be sure to follow the manual installation guide,as there are additionnal steps to do in addition to the package installation for some versions.

If you have multiple applications in the same project, as usual, you need to choose the project:

ng add @ngx-pwa/local-storage --project yourprojectname

Upgrading

To update to new versions, see the migration guides.

API

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

@Injectable()
export class YourService {
  constructor(private storage: StorageMap) {}
}

This service API follows thenew standard kv-storage API,which is similar to the standard Map API, and close to thestandard localStorage API,except it's based on RxJS Observables instead of Promises:

class StorageMap {
  // Write
  set(index: string, value: any): Observable<undefined> {}
  delete(index: string): Observable<undefined> {}
  clear(): Observable<undefined> {}

  // Read (one-time)
  get(index: string): Observable<unknown> {}
  get<T>(index: string, schema: JSONSchema): Observable<T> {}

  // Observe
  watch(index: string): Observable<unknown> {}
  watch<T>(index: string, schema: JSONSchema): Observable<T> {}

  // Advanced
  size: Observable<number>;
  has(index: string): Observable<boolean> {}
  keys(): Observable<string> {}
}

Note: there is also a LocalStorage service available,but only for compatibility with old versions of this lib.

How to

Writing data

let user: User = { firstName: 'Henri', lastName: 'Bergson' };

this.storage.set('user', user).subscribe(() => {});

You can store any value, without worrying about serializing. But note that:

  • storing null or undefined makes no sense and can cause issues in some browsers, so the item will be removed instead,
  • you should stick to JSON data, ie. primitive types, arrays and literal objects.Date, Map, Set, Blob and other special structures can cause issues in some scenarios.See the serialization guide for more details.

Deleting data

To delete one item:

this.storage.delete('user').subscribe(() => {});

To delete all items:

this.storage.clear().subscribe(() => {});

Reading data

To get the current value:

this.storage.get('user').subscribe((user) => {
  console.log(user);
});

Not finding an item is not an error, it succeeds but returns undefined:

this.storage.get('notexisting').subscribe((data) => {
  data; // undefined
});

Note you will only get one value: the Observable is here for asynchrony butis not meant to emit again when the stored data is changed.If you need to watch the value, see the watching guide.

Checking data

Don't forget it's client-side storage: always check the data, as it could have been forged.

You can use a JSON Schema to validate the data.

this.storage.get('test', { type: 'string' }).subscribe({
  next: (user) => { /* Called if data is valid or `undefined` */ },
  error: (error) => { /* Called if data is invalid */ },
});

See the full validation guide to see how to validate all common scenarios.

Subscription

You DO NOT need to unsubscribe: the Observable autocompletes (like in the Angular HttpClient service).

But you DO need to subscribe, even if you don't have something specific to do after writing in storage(because it's how RxJS Observables work).

Errors

As usual, it's better to catch any potential error:

this.storage.set('color', 'red').subscribe({
  next: () => {},
  error: (error) => {},
});

For read operations, you can also manage errors by providing a default value:

import { of } from 'rxjs';
import { catchError } from 'rxjs/operators';

this.storage.get('color').pipe(
  catchError(() => of('red')),
).subscribe((result) => {});

See the errors guide for some details about what errors can happen.

Expiration

This lib, as native localStorage and indexedDb, is about persistent storage.

Wanting temporary storage (like sessionStorage) is a very common misconception:an application doesn't need that. More details here.

Map-like operations

In addition to the classic localStorage-like API,this lib also provides a Map-like API for advanced operations:

  • .keys()
  • .has(key)
  • .size

See the documentation for more info and some recipes.For example, it allows to implement a multiple databases scenario.

Support

Angular support

We follow Angular LTS support.

This module supports Universal server-side renderingvia a mock storage.

Browser support

This lib supports the same browsers as Angular.See the browsers support guide for more details and special cases (like private browsing).

Collision

If you have multiple apps on the same subdomain and you don't want to share data between them,see the prefix guide.

Interoperability

For interoperability when mixing this lib with direct usage of native APIs or other libs like localForage(which doesn't make sense in most cases),see the interoperability documentation.

Changelog

Changelog available here, and migration guides here.

License

MIT

  • 问题-----有没有大哥看看哪里有问题 报错 renewal operation failed due to timeout 代码—(TS) AuthService import AuthenticationContext from "adal-angular"; export default class AuthService { private ctx: Authenticatio

  • 缓存的功能就是加快获取内容的速度,减少重复请求,这是一项非常重要的作用。 因此,angularJS框架中,提供了专门的服务—— cacheFactory来生成缓存,同时, http服务中还存在缓存中可以开启缓存、自定义缓存名称. info方法 info方法返回缓存对象的一些信息,包括大小、名称、代码如下。 var cache = $cacheFactory("test"); console.log

  • 原文出处:https://blog.csdn.net/hotboyboy/article/details/102825281?utm_medium=distribute.pc_relevant_t0.none-task-blog-OPENSEARCH-1.nonecase&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-OPE

  • Angular(服务、存储机制) 服务 1.provider 最大的服务,可以配置 特点 (1)moren provider 会被自动实例化 (2)在控制器中使用会调用$get (3)后续操作写在$get之后 <div ng-controller="twoCtrl"></div> <script> var app=angular.module('appModule',[]); app.confi

  •   参考链接 https://www.cnblogs.com/tarena/p/8473961.html https://www.jianshu.com/p/ddef433c30f9 https://blog.csdn.net/fen747042796/article/details/74840844 https://www.jianshu.com/p/c2d61fc76128

  • localStorage 是h5提供的客户端存储数据的新方法 之前,这些都是由 cookie 完成的,但是 cookie 不适合大量数据的存储,因为它们由每个对服务器的请求来传递,这使得 cookie 速度很慢而且效率也不高。 存储的数据类型为字典 存数据(需要存成json): localStorage.setItem() locationStorage[‘键’] = JSON.stringify

  • 感觉这篇文章不赖: https://blog.csdn.net/Q_Quiet/article/details/94283965?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522158567668619724845020401%2522%252C%2522scm%2522%253A%252220140713.130056874..%2

  • 保存:window.localStorage.setItem('名','值'); window.localStorage.setItem('token',backdata.data[2]); 查询:window.localStorage.getItem('名'); window.localStorage.getItem('token'); 删除:window.localStorage.clear(

  • const storage=window.localStorage; if(storage!=undefined){ if(storage.hasOwnProperty("cid")&&storage.getItem("cid")>0){ this.setState({ toogle:false }) } }else{ this.setState({ toogle:true }) } }

  • <!DOCTYPE html> <html ng-app="myapp"> <head>     <meta charset="UTF-8">     <title>各种service</title>     <script src="../angular-1.5.5/angular.min.js"></script>     <script>         var my=angular.mod

  • 在angualr中,一般调用了服务端接口都是异步,那如何实现异步方法执行完后再往下执行? 当函数的返回值为true时才往下执行,但是这个函数又是异步,那该怎么实现这个功能呢 ?这个时候我们就需要用到async和await来处理异步。 定义函数 async checkBeams(): Promise<boolean> { try { return aw

  • 随着互联网的快速发展,基于网页的应用越来越普遍,同时也变的越来越复杂,为了满足各种各样的需求,会经常性在本地存储大量的数据, HTML5规范提出了相关解决方案。 本地存储特性 1、数据存储在用户浏览器中 2、设置、读取方便、甚至页面刷新不失数据 3、容量较大, 储存大小约为5MB 4、只能存储字符串,可以将对象JSON.stringifyO编码后存储 先说一下sessionStorage和loca

  • 基本概念 Web Storage 中包含如下两种机制: sessionStorage 为每一个给定的源(given origin)维持一个独立的存储区域,该存储区域在页面会话期间可用(即只要浏览器处于打开状态,包括页面重新加载和恢复)。 localStorage 同样的功能,但是在浏览器关闭,然后重新打开后数据仍然存在。 这两种机制是通过 Window.sessionStorage 和 Windo

  • Local Storage和Session Storage详解 1. 来历 在HTML5中新加了Web Storage的储存方式,主要是为了弥补Cookie储存容量的不足。Web Storage分为Local Storage和 Session Storage。 2. 优缺点 优点 Web Storage 拓展了 cookie 的 4K 限制。 Web Storage 会可以将第一次请求的数据直接存

  • 背景 最近在设计调用链与日志跟踪的API,发现相比于Java与C++,Go语言中没有原生的线程(协程)上下文,也不支持TLS(Thread Local Storage),更没有暴露API获取Goroutine的Id(后面简称GoId)。这导致无法像Java一样,把一些信息放在TLS上,用于来简化上层应用的API使用:不需要在调用栈的函数中通过传递参数来传递调用链与日志跟踪的一些上下文信息。 在Ja

  • http://www.html-js.com/article/1828 在Angular中,我们可以非常方便的进行AJAX请求。我们只需要注入$http,进行一个AJAX请求 – 然后我们就能得到一个promise对象,并可以很方便的调用其中的success或者error方法。例如下面的代码: $http.get('/foo/bar' + itemId) .success(fun

  • Thread Local Storage理解 带着问题去学习 1. 什么是thread local storage? 一种计算机编程方法,使用线程本地静态或全局的内存。 2. 主要作用是什么? 避免资源竞争;当多个线程访问同一个资源时,会产生竞争。当将资源声明为thread local storage时,则不会有竞争。 使用全局对象方法的重入性;比如一个函数使用全局变量设置一个错误码(比如c库中的

 相关资料
  • angular-local-storage An Angular module that gives you access to the browsers local storage Table of contents: Get Started Video Tutorial Development Configuration setPrefix setStorageType setDefaultT

  • 支持异步加载 angular 1.x application 的模块和组件: Support use dynamic angular module: app.useModule(name) Support use origin methods to dynamic register angular components: app.controller app.services app.filter

  • 描述 (Description) 此函数将LIST中的变量设置为当前执行块的本地变量。 如果指定了多个值,则必须使用括号来定义列表。 请注意,local创建变量的本地副本,然后在封闭块终止时超出范围。 无论何时访问本地化值,都会使用本地化值,包括该块期间使用的任何子例程和格式。 语法 (Syntax) 以下是此函数的简单语法 - local LIST 返回值 (Return Value) 此函数

  • 概要 <#local name=value> 或 <#local name1=value1 name2=value2 ... nameN=valueN> 或 <#local name> capture this </#local> 这里: name: 在root中局部对象的名称。它不是一个表达式。但它可以被写作是字符串形式, 如果变量名包含保留字符,这是很有用的,比如 <#local "

  • async()函数是一个简单任务的”启动”(launcher)函数,它是本FAQ中唯一一个尚未在标准草案中投票通过的特性。我希望它能在调和两个略微不同的意见之后最终于10月份获得通过(记得随时骚扰你那边的投票委员,一定要为它投票啊?)。 下边是一种优于传统的线程+锁的并发编程方法示例(译注:山寨map-reduce哦): template<class T,class V> struct Accum

  • asynchronous operation在线程中执行,与main应用程序线程分开。 当应用程序调用方法异步执行操作时,应用程序可以在异步方法执行其任务时继续执行。 例子 (Example) 让我们举个例子来理解这个概念。 这里,程序使用IO library接受用户输入。 import 'dart:io'; void main() { print("Enter your name :"