Search code examples
javascriptangulartypescriptangular-componentsangular-httpclient

Angular component property inexplicably remains "undefined" after being set in subscribe()


Let me just preface this by saying yes, i'm using arrow functions to retain the scope of "this" (as far as I can tell anyway).

I have two properties on my component:

IsAdmin (boolean) currentRole (string)

I make an api call to fetch user roles from my backend via Angular's HttpClient, and I have a callback subscribe-method which updates above mentioned properties with the result.

However, while I can assign the role value to currentRole, the other property IsAdmin remains undefined even as I assign it, and I get no error in my f12 debugger or visual studio code via the chrome plugin.

        import { Component, OnInit } from "@angular/core";
    import { AuthorizeService, IUser } from "../authorize.service";
    import { Observable } from "rxjs";
    import { map, tap } from "rxjs/operators";
    import { HttpClient } from "@angular/common/http";

    @Component({
      selector: "app-login-menu",
      templateUrl: "./login-menu.component.html",
      styleUrls: ["./login-menu.component.scss"]
    })
    export class LoginMenuComponent implements OnInit {
      isAuthenticated: Observable<boolean>;
      public userName: Observable<string>;

      IsAdmin : boolean;
      currentRole : string;

      constructor(private authorizeService: AuthorizeService, private http : HttpClient) {

      }

      ngOnInit() {
        this.isAuthenticated = this.authorizeService.isAuthenticated();
        this.userName = this.authorizeService.getUser().pipe(map(u => u && u.name));
        const endpoint = '.../api/User/User/GetRoles';

        this.authorizeService.getUser()
          .subscribe(data => {
             this.userNameSignedIn = data.name;
          });

        this.http.get<string[]>(endpoint).
          subscribe(result => {
            this.currentRole = result[0];
            console.log("this.currentRole ", this.currentRole); //prints "admin"
            this.IsAdmin == result.includes("admin");
            console.log("this.IsAdmin", this.IsAdmin); //prints "undefined"
          }, error => console.error(error));
      }
    }

Console output is as following:

logon-menu.component.ts:37 this.currentRole  admin
logon-menu.component.ts:39 this.IsAdmin undefined

What on earth is going on here? What am I doing wrong?


Solution

  • the problem in your subscribe is that you are using ==(comparison) instead of = (assignation)

              subscribe(result => {
                this.currentRole = result[0];
                console.log("this.currentRole ", this.currentRole); //prints "admin"
                this.IsAdmin == result.includes("admin"); //<-- here is an error
                console.log("this.IsAdmin", this.IsAdmin); //prints "undefined"
              },
    

    your code should be:

              subscribe(result => {
                this.currentRole = result[0];
                this.IsAdmin = result.includes("admin");
              },