我正在研究连接到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,并且我不确定是什么引起了问题。
我的代码可能有问题吗?
答案 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
}