字符串比较无法正常工作

时间:2020-01-06 09:56:13

标签: javascript typescript

我正在研究连接到Firebase的Ionic Web项目。

我从firestore中检索了数据,并用它来确定用户是管理员还是基金经理,但是字符串比较功能不起作用。

这是我的打字稿代码。

role: string = "";
  admin: boolean = false;
  fm: boolean = false;

  constructor(private authService: AuthService, private router: Router,) { }

  ngOnInit() {
    this.fname = "";
    this.lname = "";
    this.nric = "";
    this.role = "";
    this.admin = false;
    this.fm = false;
    this.user = this.authService.getCurrentUser();
    this.getProfile();
    if (this.role = "Admin") {
      console.log("Admin")
      this.admin = true;
    }
    else {
      if (this.role = "Fund Manager") {
        console.log("Fund Manager")
      }
    }

this.getProfile()将填满this.role。当this.role"User"时,Admin变为true,并且我不确定是什么引起了问题。

我的代码可能有问题吗?

4 个答案:

答案 0 :(得分:1)

您可以使用=====。但是===运算符(严格的比较)不会自动转换类型,所以我认为更好:

if (this.role === "Admin") {
    // do something
}

添加: switch case 语句也使用严格比较,值必须是相同类型才能匹配

switch (this.role) {
    case 'Admin':
        // do something
        break;
    case 'Manager':
        // do others
        break;
}

答案 1 :(得分:0)

使用比较运算符==而不是赋值运算符=

if (this.role == "Admin") {
  console.log("Admin")
  this.admin = true;
}
else {
  if (this.role == "Fund Manager") {
    console.log("Fund Manager")
  }

答案 2 :(得分:0)

=与==(===)不同。形式是为变量赋值,后者是根据需要进行比较。因此,this.role = 'admin'始终为真。

答案 3 :(得分:0)

要为变量分配任何值,请使用=。 要比较两个值,而不考虑它们的数据类型,请使用== 要比较两个值和变量数据类型,请使用===

使用=====比较两个变量

if ( this.role == "Admin"){

   //your logic here

}

if ( this.role === "Admin"){

    //your logic here
}
相关问题