Can't change class variable inside of a function

Hi, i am trying to change a variable’s content inside of a function. The variable that i want to change is “hasAccess”, based on my web service’s response, indicating whether the user exists or not.
Unfortunately, when i try to change the variable, his value doesn’t updates. It always returns false.
Here is my class:

export class AuthServiceProvider {
  currentUser: User;
  hasAccess = false;

  constructor(public http: HttpClient) {
    console.log("Hey");
  }

   wsConnect(endPoint = "/", method = "get", data = {}){
    let apiUrl = "http://localhost:3000";
    if(method == "post"){
      return this.http.post(
        apiUrl + endPoint,
        data
      ).map((res: Response) => JSON.parse(JSON.stringify(res)));
    }
    else if(method == "get"){
      return this.http.get(
        apiUrl + endPoint
      ).map((res: Response) => JSON.parse(JSON.stringify(res)));
    }
    else if(method == "delete"){
      return this.http.delete(
        apiUrl + endPoint,
        data
      ).map((res: Response) => JSON.parse(JSON.stringify(res)));  
    }
    else if(method == "put"){
      return this.http.put(
        apiUrl + endPoint,
        data
      ).map((res: Response) => JSON.parse(JSON.stringify(res)));    
    }
  }


  login(credentials){
    if (credentials.email === null || credentials.password === null) {
      return Observable.throw("Por favor, insira seu E-mail e senha");
    } 
    else {
      return Observable.create(observer => {
        // At this point make a request to your backend to make a real check!
        this.wsConnect(
          "/authentication/user",
          "post",
          { 
            "user":{
              "email": credentials.email,
              "password": credentials.password
            }
        }).subscribe(data => {
              if(Object.keys(data.user).length > 0){
                console.log("logado");
                this.currentUser = new User('Simon', 'saimon@devdactic.com');
                **this.hasAccess = true;**
            }              
          });
        observer.next(this.hasAccess);
        observer.complete();
      });
    }
  };

}

Thanks

Observables are asynchronous rather than synchronous, as you have it written now.

So the fix would be moving your observer.next and observer.complete calls in the same block and after you set this.hasAccess.

There’s also no need to manually create an observer, as wsconnect already returns one.

1 Like

Thanks, saved my day!