Angular 角度6:将数据保存到本地存储器

Angular 角度6:将数据保存到本地存储器,angular,html,typescript,local-storage,Angular,Html,Typescript,Local Storage,我有一个数据表,显示来自外部API的数据,我希望表页上的项目/元素数量应保存在本地存储中 以下是我迄今为止所尝试的: ngOnInit() { this.moviesService.getPopularTVShows().subscribe(res => { this.dataSource = new MatTableDataSource(res.results); this.dataSource.paginator = this.paginator; thi

我有一个数据表,显示来自外部API的数据,我希望表页上的项目/元素数量应保存在本地存储中

以下是我迄今为止所尝试的:

 ngOnInit() {
  this.moviesService.getPopularTVShows().subscribe(res => {
    this.dataSource = new MatTableDataSource(res.results);
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
    localStorage.setItem(this.dataSource, this.dataSource.length);
    console.log(localStorage.length);
  });
}
当我运行我的应用程序时,控制台显示
undefined


我的代码有什么问题?欢迎任何帮助或建议,新手尝试新东西。

在将数据存储到本地存储器时,您应该定义一个键名,该数据应为字符串,值应为字符串

 localStorage.setItem('dataSource', this.dataSource.length);
要打印,应该使用getItem

console.log(localStorage.getItem('dataSource'));

首先,你应该了解它是如何工作的。在本地存储中设置/获取值的方式不正确。有关详细信息,请阅读以下内容:

您可以使用localStorage存储json数据:

示例如下所示:-

let JSONDatas = [
    {"id": "Open"},
    {"id": "OpenNew", "label": "Open New"},
    {"id": "ZoomIn", "label": "Zoom In"},
    {"id": "ZoomOut", "label": "Zoom Out"},
    {"id": "Find", "label": "Find..."},
    {"id": "FindAgain", "label": "Find Again"},
    {"id": "Copy"},
    {"id": "CopyAgain", "label": "Copy Again"},
    {"id": "CopySVG", "label": "Copy SVG"},
    {"id": "ViewSVG", "label": "View SVG"}
]

localStorage.setItem("datas", JSON.stringify(JSONDatas));

let data = JSON.parse(localStorage.getItem("datas"));

console.log(data);

当我在控制台中运行本地存储时,我得到以下信息:
storage{[object object]:“undefined”,dataSource:“undefined”,length:2}[object object]:“undefined”dataSource:“undefined”length:2_uuuuproto_uu:storage
在一个页面中,我每页显示5项,我还需要更改什么?使用JSON.parse将objectI更改后的数据源解析为items现在可以正常工作,感谢可能的副本。请参阅此链接(对LocalStorage和SessionStorage的完整解释):