Html Angular 6:将数据保存到本地存储

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51536262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 15:43:33  来源:igfitidea点击:

Angular 6: saving data to local storage

angularhtmltypescriptlocal-storage

提问by The Dead Man

I have a data table which display data from external API, I want the number of items /element on the table page should be saved in local storage

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

Here is what I have tried so far:

这是我迄今为止尝试过的:

 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);
  });
}

When I run my app, the console displays undefined

当我运行我的应用程序时,控制台显示 undefined

What is wrong with my code? any help or suggestion is welcomed, newbie trying new stuff.

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

回答by Sajeetharan

You should define a key name while storing data to local storage which should be a string and value should be a string

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

 localStorage.setItem('dataSource', this.dataSource.length);

and to print, you should use getItem

并打印,你应该使用 getItem

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

回答by Ramesh Rajendran

First you should understand how localStorageworks. you are doing wrong way to set/get values in local storage. Please read this for more information : How to Use Local Storage with JavaScript

首先,您应该了解localStorage 的工作原理。您在本地存储中设置/获取值的方法错误。请阅读本文以获取更多信息:如何使用 JavaScript 使用本地存储