类型错误:无法读取未定义的属性“模块”
2018-01-30
3678
我是 Angular 新手,我试图在我的应用程序中使用 localStorage API。每当我运行该应用程序时,它都会在控制台中抛出错误
TypeError: localStorage.getItems 不是一个函数
。然后,我在
npm
的帮助下下载了
angular-local-storage
。我还在
app.module.ts
中导入了
LocalStorageModule
,并将其添加到导入数组中。但是,现在它抛出了这个错误:
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 {}
有人可以帮我解决这个问题吗?
提前致谢。
2个回答
localstorage
API 内置于 Angular 框架中,您不需要外部库。您可以通过
localStorage.<yourMethodName>
直接在代码中使用它
此外,没有任何名为
getItems
的方法。
可用方法列表为...
getItem
removeItem
setItem
clear
Abhilash Rathod
2018-01-30
标准 localStorage API 应该可以正常工作,无需为此安装模块,使用通常的方式获取和设置 localStorage 中的项目:
localStorage.setItem('name', 'ABC');
localStorage.getItem('name');
Manu
2018-01-30