0

I have the following UserService where I'm simply having a property within the instance that determines whether the user isAuthenticated. For some reason, even though the value is being changes by setting this.isAuthenticated to various value, on logout and some other methods, that change is not being caught by Angular. I even tried doing a manual $digest and $apply but still no luck.

export default class UserService {

  constructor($http, $state, AppConstants, JWTService) {
    'ngInject';

    this.$http = $http;
    this.$state = $state;

    this.isAuthenticated = false;
  }


  logout() {
    this.isAuthenticated = false;
    this.$state.go('login', null, { reload: true });
  }

  verify() {
    return new Promise((resolve) => {

      // if a user exists, then resolve
      if (this.isAuthenticated) {
        return resolve(true);
      }

      this.$http({
        method: 'POST',
        url: `${this.AppConstants.api}/verify`
      })
      .then(() => {
        this.isAuthenticated = true;
        return resolve(true);
      })
      .catch(() => {
        this.isAuthenticated = false;
        return resolve(false);
      });
    });
  }

}

The code works and when I login the first time, I set the this.isAuthenticated to true and the this.verify works by posting. However, when I logout, even though the this.isAuthenticatd is so to false, the condition if (this.isAuthenticated) is still true when this.verify is called again.

Detuned
  • 3,652
  • 4
  • 27
  • 54

1 Answers1

0

"this" is not what you think it is inside your .then() function. The scope has changed. This scenario is common and just something you have to constantly keep in mind when working in javascript. Here is just one example of what you can do about it:

javascript promises and "this"

Community
  • 1
  • 1
Dan
  • 3,583
  • 1
  • 23
  • 18
  • I know what the `this` is, as the context remains the same, given we're using the fat arrow syntax. I've already tested that to ensure we're in the same context. – Detuned Apr 19 '17 at 15:05