我是Angular的新手,我试图在我的应用程序中使用localStorage API。每当我运行应用程序时,它会在控制台中抛出错误TypeError: localStorage.getItems is not a function
。然后我在npm的帮助下下载了angular-local-storage
。我还在LocalStorageModule
中导入了app.module.ts
并将其添加到导入数组中。但是,现在它会抛出此错误:
angular-localstorage.js:24 Uncaught TypeError: Cannot read property 'module' of undefined
at TEST (angular-localstorage.js:24)
at eval (angular-localstorage.js:198)
at Object.../../../../angular-localstorage/angular-localstorage.js (vendor.bundle.js:206)
at __webpack_require__ (inline.bundle.js:55)
at eval (index.js:1)
at Object.../../../../angular-localstorage/index.js (vendor.bundle.js:213)
at __webpack_require__ (inline.bundle.js:55)
at eval (app.module.ts:7)
at Object.../../../../../src/app/app.module.ts (main.bundle.js:36)
at __webpack_require__ (inline.bundle.js:55)<br/>
代码包含getItem函数:
export class Init{
load(){
if(localStorage.getItem('markers')===null || localStorage.getItem('markers')===undefined)
{
console.log('No markers found...creating...');
var markers=[
{
name:'Company One',
lat:42.825588,
lng:-71.018029,
draggable:true
},
{
name:'Company Two',
lat:42.868170,
lng:-70.889071,
draggable:false
},
{
name:'Company Three',
lat:42.858279,
lng:-71.930498,
draggable:true
}
];
localStorage.setItem('markers',JSON.stringify(markers));
}
else
{
console.log('Loading markers...')
}
}
}
app.module.ts中的代码:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ApplicationRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import {MarkerService} from './services/marker.service';
import {LocalStorageModule} from 'angular-localstorage';
import { AgmCoreModule } from '@agm/core';
@NgModule({
imports: [
BrowserModule,
CommonModule,
FormsModule,
LocalStorageModule,
AgmCoreModule.forRoot({
apiKey:''
})
],
providers: [MarkerService],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule {}
任何人都可以帮我解决这个问题 在此先感谢。
答案 0 :(得分:2)
localstorage
API内置于Angular框架中,您不需要外部库。您可以localStorage.<yourMethodName>
直接将其用于代码
此外,还没有任何名为getItems
的方法。
可用方法列表是......
getItem
removeItem
setItem
clear
答案 1 :(得分:1)
标准的localStorage API应该可以正常工作,不需要为此安装模块,使用通常的方法来获取和设置localStorage中的项目:
localStorage.setItem('name', 'ABC');
localStorage.getItem('name');