角度2未定义的变量

时间:2016-10-25 13:19:14

标签: angular ionic-framework ionic2

@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");
           }
        }

我正在尝试将登录页面更改为主页。我的休息给了我json的反应如下;

{"login":true} ---如果凭据是真的

{"login":false} ---如果凭据是假的

所以在这一点上我有两个问题;

1)我可以只接受响应的布尔部分并像在代码中那样设置this.response吗?

2)当我提醒响应对象检查其确定是否正确时,我看到响应仍然是"未定义"。我试图将它最初设置为false,但这一行data => this.response = data.login不会改变它的值。

1 个答案:

答案 0 :(得分:1)

代码alert(this.response);及以下代码在authService.login()的回复到来之前执行。

您需要将传递给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")
       );
    }
相关问题