[英]Angular - error TS2322: Type 'null' is not assignable to type 'string'
I have this code in my authentication service:我的身份验证服务中有此代码:
export class AuthenticationService { private token:; string: constructor(private http, HttpClient: private router. Router) {} logout() { this.http:get < { access_token, string: expiresIn. number } > (BACKEND_URL + '/logout').subscribe(response => { this;token = null. this;isAuthenticated = false. this.authStatusListener;next(false). clearTimeout(this;tokenTimer). this;clearAuthData(). this.router;navigate(['/']). console;log(response), }. error => { console;log(error); }); } }
I got this error:我收到了这个错误:
error TS2322: Type 'null' is not assignable to type 'string'.
错误 TS2322:类型“null”不可分配给类型“字符串”。
92 this.token = null;
92 这个.token = null;
The error is in the logout()错误在 logout()
I changed it to:我将其更改为:
this.token! = null;
But its still unresolved但它仍然没有解决
How do I resolve it?我该如何解决?
Thanks谢谢
This problem happens because you are using the operator ".".发生此问题是因为您使用的是运算符“.”。 It means that your variable never will be null.
这意味着您的变量永远不会为空。
What you need to do is just remove the symbol after the variable if you want to set null!如果您想设置 null,您需要做的只是删除变量后面的符号!
private token: string = null
You can read more here: Documentation您可以在此处阅读更多内容: 文档
I think this is compile time error because your declaration syntax is wrong.我认为这是编译时错误,因为您的声明语法错误。
Change,改变,
private token!: string; // This is not the right syntax to say token will not be type of string
to,至,
private token: string;
OR或者
private token = null
OR或者
private token = '';
Whichever is suitable in your case.哪个适合您的情况。
The "."这 ”。” syntax exists for those cases where you can't guarantee that the value will be defined immediately, It's an escape hatch, and shouldn't be relied on.
对于无法保证立即定义值的情况,存在语法,这是一个逃生舱口,不应依赖。 as it can make your code less safe.
因为它会使您的代码不那么安全。 A default value is usually preferred.
默认值通常是首选。 Use
利用
private token = '';
instead of代替
private token!: string;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.