can can - 1 month ago 16
AngularJS Question

angular 2 undefined variable

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

username: string;
password: string;
firm: string;
response : boolean;


constructor(public navCtrl: NavController, public authService: Auth, public loadingCtrl: LoadingController) {

}

login(){
let credentials = [this.username, this.password, this.firm];
this.authService.login(credentials)
.subscribe(
data => this.response = data.login,
error => alert(error),
() => console.log("Finished")
);
alert(this.response);
if(this.response){
this.navCtrl.setRoot(HomePage);
}else{
alert("check your credentials");
}
}


I am trying to change the login page to home page. My rest gives me the json response like following;

{"login":true}
--- if credentials are true

{"login":false}
--- if credentials are false

so at this point I have two question;

1) Can I take just the boolean part of the response and set the this.response to it like in the code?

2)when I alert the response object to check its settled correctly or not, I see that response is still "undefined". I tried to set it initially to false but this line
data => this.response = data.login
does not change its value.

Answer

The code alert(this.response); and below is executed before the response from authService.login() arrives.

You need to move the code inside the callback passed to subscribe

    login(){
       let credentials = [this.username, this.password, this.firm];
       this.authService.login(credentials)
       .subscribe(
           data => {
             this.response = data.login;
               alert(this.response);
               if(this.response){
                   this.navCtrl.setRoot(HomePage);
               }else{
                   alert("check your credentials");
               }
           },
           error => alert(error),
           () => console.log("Finished")
       );
    }