Angular - 错误 TS2345:'string | 类型的参数 |null' 不能分配给类型为 'string' 的参数 [英] Angular - error TS2345: Argument of type 'string | null' is not assignable to parameter of type 'string'

查看:41
本文介绍了Angular - 错误 TS2345:'string | 类型的参数 |null' 不能分配给类型为 'string' 的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的身份验证服务中有这个:

I have this in my authentication service:

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('user')

localStorage.getItem('user')

但是得到这个错误:

错误 TS2345:'string 类型的参数 |null' 不能分配给类型为 'string' 的参数

error TS2345: Argument of type 'string | null' is not assignable to parameter of type 'string'

如何解决这个问题?

谢谢

推荐答案

显然,您需要检查 localStorage 条目是否未设置键 'user'.喜欢什么

Apparently you need to check against localStorage entry for key 'user' not being set. Sth like

const userJSON = localStorage.getItem('user');

if (userJSON) {
   // token setting logic goes here
} else {
   // plan B
}

这篇关于Angular - 错误 TS2345:'string | 类型的参数 |null' 不能分配给类型为 'string' 的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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