angular-async-local-storage

我要开发同款
匿名用户2021年12月09日
46阅读
开发技术JavaScript
所属分类Web应用开发、Web框架
授权协议MIT License

作品详情

AsynclocalstorageforAngular

Efficientclient-sidestoragemoduleforAngular:

simplicity:simpleAPIlikenativelocalStorage,perfomance:internallystoredviatheasynchronousindexedDBAPI,Angular-like:wrappedinRxJSObservables,security:validatedatawithaJSONSchema,compatibility:worksaroundsomebrowsersissuesandheavilytestedviaGitHubActions,documentation:APIfullyexplained,andachangelog!Sponsorship

Youlikethislibrarydownloadedmorethan15000timeseachweekonnpm?Youliketheseriousopensourcework(fulldocumentation,libreadyondayoneofAngularmajorupdates,...)?Andyourcompanyisusingitinprojectsgeneratingmoney?

Well,onmyside,it'salotofunpaidwork.Sopleaseconsider:

becomingaregularsponsordoingaone-timedonationatleast,taking2minutestoshowyourloveBythesameauthorAngularschematicsextensionforVSCode(GUIforAngularCLIcommands)typescript-strictly-typed:reliablecodewithTypeScriptstrictlytypedPopularAngularpostsonMediumFollowupdatesofthislibonTwitterAngulartrainings(inFrench,asI'mbasedinParis,butmyEnglishbioishereanditcanbedoneremotely)Whythismodule?

Fornow,Angulardoesnotprovideaclient-sidestoragemodule,andalmosteveryappneedssomeclient-sidestorage.Thereare2nativeJavaScriptAPIsavailable:

localStorageindexedDB

ThelocalStorageAPIissimpletousebutsynchronous,soifyouuseittoooften,yourappwillsoonbegintofreeze.

TheindexedDBAPIisasynchronousandefficient,butit'samesstouse:you'llsoonbecaughtbythecallbackhell,asitdoesnotsupportPromisesyet.

MozillahasdoneaverygreatjobwiththelocalForagelibrary:asimpleAPIbasedonnativelocalStorage,butinternallystoredviatheasynchronousindexedDBforperformance.Butit'sbuiltinES5oldschoolwayandthenit'samesstoincludeintoAngular.

ThismoduleisbasedonthesameideaaslocalForage,butbuiltinES6+andadditionallywrappedintoRxJSObservablestobehomogeneouswithotherAngularmodules.

Gettingstarted

Installthepackage,accordingtoyourAngularversion:

#ForAngularLTS(Angular>=10):ngadd@ngx-pwa/local-storage

Done!

Youshouldsticktothesecommands.Ifforanyreasonngadddoesnotwork,besuretofollowthemanualinstallationguide,asthereareadditionnalstepstodoinadditiontothepackageinstallationforsomeversions.

Ifyouhavemultipleapplicationsinthesameproject,asusual,youneedtochoosetheproject:

ngadd@ngx-pwa/local-storage--projectyourprojectnameUpgrading

Toupdatetonewversions,seethemigrationguides.

APIimport{StorageMap}from'@ngx-pwa/local-storage';@Injectable()exportclassYourService{constructor(privatestorage:StorageMap){}}

ThisserviceAPIfollowsthenewstandardkv-storageAPI,whichissimilartothestandardMapAPI,andclosetothestandardlocalStorageAPI,exceptit'sbasedonRxJSObservablesinsteadofPromises:

classStorageMap{//Writeset(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>{}//Observewatch(index:string):Observable<unknown>{}watch<T>(index:string,schema:JSONSchema):Observable<T>{}//Advancedsize:Observable<number>;has(index:string):Observable<boolean>{}keys():Observable<string>{}}

Note:thereisalsoaLocalStorageserviceavailable,butonlyforcompatibilitywitholdversionsofthislib.

HowtoWritingdataletuser:User={firstName:'Henri',lastName:'Bergson'};this.storage.set('user',user).subscribe(()=>{});

Youcanstoreanyvalue,withoutworryingaboutserializing.Butnotethat:

storingnullorundefinedmakesnosenseandcancauseissuesinsomebrowsers,sotheitemwillberemovedinstead,youshouldsticktoJSONdata,ie.primitivetypes,arraysandliteralobjects.Date,Map,Set,Blobandotherspecialstructurescancauseissuesinsomescenarios.Seetheserializationguideformoredetails.Deletingdata

Todeleteoneitem:

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

Todeleteallitems:

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

Togetthecurrentvalue:

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

Notfindinganitemisnotanerror,itsucceedsbutreturnsundefined:

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

Noteyouwillonlygetonevalue:theObservableishereforasynchronybutisnotmeanttoemitagainwhenthestoreddataischanged.Ifyouneedtowatchthevalue,seethewatchingguide.

Checkingdata

Don'tforgetit'sclient-sidestorage:alwayscheckthedata,asitcouldhavebeenforged.

YoucanuseaJSONSchematovalidatethedata.

this.storage.get('test',{type:'string'}).subscribe({next:(user)=>{/*Calledifdataisvalidor`undefined`*/},error:(error)=>{/*Calledifdataisinvalid*/},});

Seethefullvalidationguidetoseehowtovalidateallcommonscenarios.

Subscription

YouDONOTneedtounsubscribe:theObservableautocompletes(likeintheAngularHttpClientservice).

ButyouDOneedtosubscribe,evenifyoudon'thavesomethingspecifictodoafterwritinginstorage(becauseit'showRxJSObservableswork).

Errors

Asusual,it'sbettertocatchanypotentialerror:

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

Forreadoperations,youcanalsomanageerrorsbyprovidingadefaultvalue:

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

Seetheerrorsguideforsomedetailsaboutwhaterrorscanhappen.

Expiration

Thislib,asnativelocalStorageandindexedDb,isaboutpersistentstorage.

Wantingtemporarystorage(likesessionStorage)isaverycommonmisconception:anapplicationdoesn'tneedthat.Moredetailshere.

Map-likeoperations

InadditiontotheclassiclocalStorage-likeAPI,thislibalsoprovidesaMap-likeAPIforadvancedoperations:

.keys().has(key).size

Seethedocumentationformoreinfoandsomerecipes.Forexample,itallowstoimplementamultipledatabasesscenario.

SupportAngularsupport

WefollowAngularLTSsupport.

ThismodulesupportsUniversalserver-siderenderingviaamockstorage.

Browsersupport

ThislibsupportsthesamebrowsersasAngular.Seethebrowserssupportguideformoredetailsandspecialcases(likeprivatebrowsing).

Collision

Ifyouhavemultipleappsonthesamesubdomainandyoudon'twanttosharedatabetweenthem,seetheprefixguide.

Interoperability

ForinteroperabilitywhenmixingthislibwithdirectusageofnativeAPIsorotherlibslikelocalForage(whichdoesn'tmakesenseinmostcases),seetheinteroperabilitydocumentation.

Changelog

Changelogavailablehere,andmigrationguideshere.

License

MIT

声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论