我试图将matSortDirection存储在本地存储中,但在检索时给出错误 "字符串"不能分配给类型"排序方向":
public sortData(sort: Sort)
{
localStorage.setItem('xyz', sort.active)
localStorage.setItem('abc', sort.direction)
}
let PGDirection:string= String(localStorage.getItem('abc'))
this.dataSource = new MatTableDataSource(sourceName);
this.dataSourceLength = sourceName.length;
this.sort.active = PGActive;
this.sort.direction=PGDirection;
错误消息基本上告诉您整个故事。
sort.direction
似乎具有 SortDirection 类型。本地存储只能存储字符串。
当您使用localStorage.setItem('abc', sort.direction)
时,它会尝试将sort.direction
转换为字符串。您应该手动执行此操作:JSON.stringify(sort.direction)
.
现在,当您从localStorage检索此对象时,您需要将其转换回SortDirection对象。像JSON.parse(localStorage.getItem('abc'))
.
所以你的代码应该看起来像这样:
public sortData(sort: Sort) {
localStorage.setItem('xyz', JSON.stringify(sort.active))
localStorage.setItem('abc', JSON.stringify(sort.direction))
}
let PGDirection: SortDirection = JSON.parse(localStorage.getItem('abc'))
this.dataSource = new MatTableDataSource(sourceName);
this.dataSourceLength = sourceName.length;
this.sort.active = PGActive;
this.sort.direction=PGDirection;
不确定 SortDirection 是接口还是类。如果它是一个类,则可能需要在从 localStorage 检索数据后调用它的构造函数。