Angular 6:将数据保存到本地存储 [英] Angular 6: saving data to local storage

查看:842
本文介绍了Angular 6:将数据保存到本地存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是我到目前为止尝试过的:

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

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

When I run my app, the console displays undefined

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

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

推荐答案

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

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

要打印,您应该使用getItem

and to print, you should use getItem

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

这篇关于Angular 6:将数据保存到本地存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆