[英]Angular2/TypeScript: error TS2345: Argument of type 'String' is not assignable to parameter of type 'string'
[英]Angular - error TS2345: Argument of type 'string | null' is not assignable to parameter of type 'string'
我的身份验证服务中有这个:
constructor(private http: HttpClient, private router: Router,) {
//append headers
// set token if saved in local storage
var currentUser = JSON.parse(localStorage.getItem('user'));
this.token = currentUser && currentUser.token;
if(this.token){
this.user_id = currentUser.user.user_id;
}
}
这有下划线:
localStorage.getItem('用户')
但是得到了这个错误:
错误 TS2345:类型为“字符串”的参数 | null' 不能分配给“字符串”类型的参数
我该如何解决这个问题?
谢谢
显然,您需要检查未设置关键'user'
localStorage 条目。 某事喜欢
const userJSON = localStorage.getItem('user');
if (userJSON) {
// token setting logic goes here
} else {
// plan B
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.