Ionc2 / Angular2 Page不反映变化

时间:2017-02-02 16:43:48

标签: javascript angular typescript ionic2

我正在使用Ionic2 rc4。我有一个登录表单。

enter image description here

如您所见,Sign In按钮已被禁用。

我的问题是它只应在表单无效时禁用。但是,当表单有效时,即有EmailPassword时,不应禁用该表单。

当我输入EmailPassword时,它会保持禁用状态,但是如果我将焦点从浏览器切换回来,然后再返回到它,则会启用它。就好像页面没有刷新到正确的状态。

问题

有没有办法在表单有效时立即启用此功能?

loginemail.html

<ion-header>
  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>Login</ion-title>
  </ion-navbar>
</ion-header>


<ion-content padding>

  <form [formGroup]="loginForm" (ngSubmit)="submit()">
    <ion-item>
      <ion-label floating>Email</ion-label>
      <ion-input type="text" formControlName="email" id="email" [(ngModel)]="personModel.emailAddress"></ion-input>
    </ion-item>
    <control-messages class="error-box" [control]="loginForm.controls.email"></control-messages>
    <ion-item>
      <ion-label floating>Password</ion-label>
      <ion-input type="password" formControlName="password" id="password"></ion-input>
    </ion-item>
    <control-messages class="error-box" [control]="loginForm.controls.password"></control-messages>
    <br/>
    <ion-buttons>
      <button ion-button class="form-button-text" type="submit" [disabled]="!loginForm.valid" block round>Sign In</button>
    </ion-buttons>
  </form>
  <br/><br/>
  <p (click)="forgotPassword()" class="small-text">Forgot email or password?</p>
  <br/><br/><br/><br/>
  <button ion-button color="light" (click)="register()" color="dark" clear block round class="form-button-text">Quick Sign up</button>

</ion-content>

loginemail.ts

import { Component, Input, Inject, forwardRef } from '@angular/core';
import { NavController, NavParams, ViewController, AlertController, MenuController, Events, Loading, LoadingController } from 'ionic-angular';
import { FirebaseAuth } from 'angularfire2';
import { ValidationService } from '../validation/validationService';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { RegisterPage } from '../register/register';
import { ForgotPage } from '../forgot/forgot';
import { PersonModel } from '../model/personModel';
import { PersonService } from '../service/personService';
import { UtilityService } from '../utils/utilityService';
import { PersonPage } from '../person/person';

@Component({
    templateUrl: 'loginemail.html'
})

export class LoginEmailPage {

    public loginForm: FormGroup;
    public errorMessage: string;
    public personModel: PersonModel = null;
    public personService: PersonService = null;
    public personLoggedIn: boolean = false;
    public menu: MenuController = null;
    public utilityService: UtilityService = null;
    public events: Events = null;
    public loading: Loading = null;
    public alertCtrl: AlertController = null;
    public fireAuth: firebase.auth.Auth;
    public userProfile: firebase.database.Reference;

    @Input() control: FormControl;

    constructor(@Inject(forwardRef(() => UtilityService)) utilityService, public auth: FirebaseAuth, menu: MenuController, public nav: NavController, 
        public navParams: NavParams, public builder: FormBuilder, public viewCtrl: ViewController, alertCtrl: AlertController, 
        personService: PersonService, events: Events, public loadingCtrl: LoadingController) {
        this.fireAuth = firebase.auth();
        this.userProfile = firebase.database().ref('/userProfile');
        this.loginForm = builder.group({
            'email': ['', [Validators.required, Validators.minLength(3), Validators.maxLength(55), ValidationService.emailValidator, (control) => ValidationService.personEmailNotExists(control, this.personService)]],
            'password': ['', [Validators.required, Validators.minLength(5), Validators.maxLength(45), ValidationService.passwordValidator]]
        });
        this.alertCtrl = alertCtrl;
        this.events = events;
        this.utilityService = utilityService;
        this.menu = menu;
        this.personModel = this.navParams.get('personModel');
        if (!this.personModel) {
            this.personModel = new PersonModel();
        }
        this.personService = personService;
    }

    submit() {
        this.loading = this.loadingCtrl.create({
            content: 'Please wait...'
        });
        if (this.loginForm.dirty && this.loginForm.valid) {
            this.loading.present().then(() => {
                this.checkCredentials(this.loginForm.value.email, this.loginForm.value.password).then(() => {
                    if (this.personLoggedIn === true) {
                        this.loginFirebaseUser(this.loginForm.value.email, this.loginForm.value.password).then((authData) => {
                            let user: firebase.User = this.fireAuth.currentUser;
                            if (!user) {
                                this.auth.subscribe((authData) => {
                                    this.login(authData.auth);
                                });
                            } else {
                                this.login(user);
                            }
                        }).catch((error) => {
                            console.error('Error trying to login ', error);
                            this.loading.dismiss().then(() => {
                                this.doAlert(error.message);
                            });
                        });
                    }
                    this.loading.dismiss();
                });
            });
        }
    }

    login(firebaseUser: firebase.User): void {
        let promise: Promise<any> = this.utilityService.login(this.personModel, firebaseUser, this.nav, this.auth, this.fireAuth, false);
        if (promise) {
            promise.then(() => {
                let data = {
                    person: this.personModel
                }
                this.events.publish('push:notifications', data);
                this.loading.dismiss().then(() => {
                    if (this.navParams.get('fromReview')) {
                        this.nav.pop();
                    } else if (this.navParams.get('fromChat')) {
                        this.nav.pop();
                    } else {
                        this.nav.setRoot(PersonPage);
                    }
                });
            }, error => {
                this.utilityService.logout(this.auth, this.fireAuth).then(() => {
                    this.utilityService.setUpMenuItems();
                    this.auth.logout();
                });
                this.loading.dismiss().then(() => {
                    let alert = this.alertCtrl.create({
                        message: error.message,
                        buttons: [
                            {
                                text: "Ok",
                                role: 'cancel'
                            }
                        ]
                    });
                    alert.present();
                });
            });
        } else {
            this.loading.dismiss();
        }
    }

    checkCredentials(email: string, password: string): any {
        let promiseUsername: Promise<PersonModel> = this.personService.getPersonByEmail(email);
        return promiseUsername.then((personModel: PersonModel) => {
            if (personModel.emailAddress != email) {
                this.doAlert('Email does not exist.');
            } else {
                if (personModel.emailAddress === this.loginForm.value.email) {
                    this.personModel = personModel;
                    this.personLoggedIn = true;
                } else {
                    this.personLoggedIn = false;
                    this.doAlert('Password does not match Username.');
                }
            }
        });
    }

    doAlert(msg: string) {
        this.loading.dismiss().then(() => {
            let alert = this.alertCtrl.create({
                title: 'Login',
                subTitle: msg,
                buttons: ['Dismiss']
            });
            alert.present().then(() => {
                this.loading.dismiss();
            });
        });
    }


    register() {
        this.nav.push(RegisterPage, {
        })
    }

    forgotPassword() {
        this.nav.push(ForgotPage, {
            personModel: this.personModel
        });
    }

    loginFirebaseUser(email: string, password: string): firebase.Promise<boolean> {
        return this.fireAuth.signInWithEmailAndPassword(email, password).then(() => {
            console.log('signInWithEmailAndPassword', email, password);
        }).catch((error)=> {
            console.error('Error signInWithEmailAndPassword', email, password, error.name, error.message);
            throw new Error(error.message);
        });
    }
}

更新

根据下面的建议,我尝试在Promise中包装firebase调用,但不幸的是,这没有任何区别。

                    return new Promise<any>(() => {
                        this.loginFirebaseUser(this.loginForm.value.email, this.loginForm.value.password).then((authData) => {
                            let user: firebase.User = this.fireAuth.currentUser;
                            if (!user) {
                                this.auth.subscribe((authData) => {
                                    this.login(authData.auth);
                                });
                            } else {
                                this.login(user);
                            }
                        }).catch((error) => {
                            console.error('Error trying to login ', error);
                            this.loading.dismiss().then(() => {
                                this.doAlert(error.message);
                            });
                        });
                    });

2 个答案:

答案 0 :(得分:0)

尝试为您的电子邮件和密码字段设置名称

<ion-input type="text" formControlName="email" id="email" name="email" [(ngModel)]="personModel.emailAddress"></ion-input>

<ion-input type="password" formControlName="password" name="password" id="password"></ion-input>

这样,loginForm就会引用这些元素进行验证。

答案 1 :(得分:0)

我遇到了同样的问题。 看起来像使用firebase以及Ionic 2中断表单,输入,按钮等。

我已经为此开了github issue,我不是第一个。

我作为一种解决方法所做的是将每个对firebase的调用封装在一个promisse中(参见链接中的一个示例),它为我解决了。在app.components中使用auth.onAuthStateChanged也存在一些问题,我还没有尝试过,但是将它放在Observable中也可能是一个蠢货。

所以,问题是使用firebase promisses和ionic2 / angular2,打字稿promisses工作正常,并没有打破你的应用程序。