Angular - 错误 TS2322:类型 'null' 不可分配给类型 'string'

时间:2021-05-31 11:50:50

标签: angular

我的身份验证服务中有此代码:

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);
      });
  }

}

我收到此错误:

<块引用>

错误 TS2322:类型 'null' 不能分配给类型 'string'。

<块引用>

92 this.token = null;

错误在 logout()

我改成:

this.token! = null;

但还是没有解决

我该如何解决?

谢谢

3 个答案:

答案 0 :(得分:0)

出现这个问题是因为您使用了运算符“!”。这意味着您的变量永远不会为空。

如果你想设置null,你需要做的就是删除变量后面的符号!

private token: string = null

您可以在此处阅读更多信息:Documentation

答案 1 :(得分:0)

我认为这是编译时错误,因为您的声明语法错误。

改变,

private token!: string;   // This is not the right syntax to say token will not be type of string

到,

private token: string;

private token = null

private token = '';

哪个适合您的情况。

答案 2 :(得分:0)

“!”对于无法保证立即定义值的情况,存在语法。这是一个逃生舱口,不应该被依赖,因为它会使您的代码不那么安全。默认值通常是首选。 使用

private token = '';

代替

private token!: string;