简体   繁体   中英

Angular - error TS2345: Argument of type 'string | null' is not assignable to parameter of type '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;
   }
}

This is underlined:

localStorage.getItem('user')

But got this error:

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

How do I get this resolved?

Thanks

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM