-1

I am working on an Ionic web project connected to firebase.

I retrieved data from firestore and use it to determine if the user is an admin or fund manager, but the string comparison function does not work.

Here is my typescript code.

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() would fill up this.role. When this.role is "User", Admin becomes true, and I am not sure what is causing the problem.

Could there be any problems with my code?

k0pernikus
  • 41,137
  • 49
  • 170
  • 286
  • I suggest you use a linter to catch these kind of potential bugs. When using [tslint](https://palantir.github.io/tslint/), you could find this issue via the [no-conditional-assignment rule](https://palantir.github.io/tslint/rules/no-conditional-assignment/). – k0pernikus Jan 06 '20 at 10:13

5 Answers5

1

You can use === or ==. But === operator (strict comparasion) will not auto-cast type, so I think it is better:

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

Addition: switch case statement also use strict comparison, values must be the same type to match

switch (this.role) {
    case 'Admin':
        // do something
        break;
    case 'Manager':
        // do others
        break;
}
Văn Quyết
  • 1,625
  • 11
  • 23
0

use comparison operator == rather than assignment operator =

if (this.role == "Admin") {
  console.log("Admin")
  this.admin = true;
}
else {
  if (this.role == "Fund Manager") {
    console.log("Fund Manager")
  }
Mridul
  • 1,135
  • 1
  • 2
  • 18
0

= is different from ==(===).The formal is to assign a value to a variable, the latter is to make a comparison what you want.So here this.role = 'admin' is always true.

fengxh
  • 369
  • 2
  • 8
0

To assign any value to the variable use =. To compare two values irrespective of their data type use == To compare two values along with variables data type use ===

Use == or === to compare two variables

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

   //your logic here

}

or

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

    //your logic here
}
Darpan Rangari
  • 995
  • 6
  • 20
0

You don't compare, you're assigning a value. In addition to the already given answers: You can use YODA Condition style to avoid mistakes like this. If you write the code like if( "Admin" = this.role) would automatically cause an error which will be shown in the console of your browser.