在我的角-11 config.service中,我使用:
var currentUser = JSON.parse(localStorage.getItem('user'));我发现了一个错误:
error TS2345:类型为'string‘的参数不能分配给'string’类型的参数。输入'null‘不能分配到输入'string’。10 var currentUser = JSON.parse(localStorage.getItem('user'));
然后当我把它改为:
this.currentUser = JSON.parse(localStorage.getItem('currentUser') || '{}');此错误变成:
src/app/core/services/config.service.ts:11:1 -错误TS2532: Object可能是“未定义”。11 JSON.parse(localStorage.getItem('currentUser') this.currentUser ={});
然后"this“加下划线。
对象可能是“未定义”
我怎样才能解决这个问题?
谢谢
发布于 2021-05-25 11:02:46
这是正确的做法:
this.currentUser = JSON.parse(localStorage.getItem('currentUser')!) || {};这是因为:
尽管从TS的角度来看,null
JSON.parse(localStorage.getItem('currentUser')!)在本地存储中返回对象,或者在|| {}中返回,您可以说,它肯定会返回。发布于 2021-05-25 11:09:27
我会说些更详细的话:
const currentUserFromStorage = localStorage.getItem('currentUser') as string;
const currentUser = !!currentUserFromStorage ? JSON.parse(currentUserFromStorage) : {};https://stackoverflow.com/questions/67686537
复制相似问题