1

I'm having an issue setting a class variable from within an Observable.create() statement. The variable stays undefined. (Not sure that this matters but this is using the ionic framework). The AuthenticationService is "injected" once in the app.module.ts..

Injectable class (where I'm trying to set the currentUser variable):

@Injectable()
export class AuthenticationService {
    currentUser: User;

    login(email, password): Observable<boolean> {
        return Observable.create(function(observer) {
            var loggedIn = true; //Do call to login service

            if(loggedIn) {
                this.currentUser = new User("Test_Fname", "Test_Lname");
            }

            observer.next(loggedIn);
            observer.complete();        
        });
    }
}

Controller (where I'm calling the login function):

import { AuthenticationServiceProvider, Credentials } from '../../providers/authentication-service/authentication-service';

@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {
  constructor(private authService: AuthenticationServiceProvider) {

  }

  login() {
    this.authService.login("test@test.com", "password123!")
    .subscribe(authenticated => {
        if(authenticated) {
          console.log("Logged in!");        
          console.log(this.authService.currentUser); // UNDEFINED!!!  
        } else { 
          console.log("Login failed!");
        }
      }
    );
  }  
}

I can see the "Logged in!" console message, however the currentUser is still undefined. If I set the currentUser from outside the Observable.create() it works just fine. Am I doing it wrong?

Thanks.

JeanJacques
  • 1,754
  • 1
  • 12
  • 25
Milkshake
  • 31
  • 7
  • 1
    `[angularjs]` != `[angular]`. Be careful with tags! ;-) – Mistalis Aug 22 '17 at 14:37
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – n00dl3 Aug 22 '17 at 14:53

1 Answers1

0

Use the arrow function =>. When you use the function keyword, you lose the access to this. Change your code to the below instead:

login(email, password): Observable<boolean> {
    return Observable.create( observer => {
        var loggedIn = true; //Do call to login service

        if(loggedIn) {
            this.currentUser = new User("Test_Fname", "Test_Lname");
        }

        observer.next(loggedIn);
        observer.complete();        
    });
}
halfer
  • 19,824
  • 17
  • 99
  • 186
FAISAL
  • 33,618
  • 10
  • 97
  • 105