只需使用 authState 。它对我有用
constructor(public afAuth:AngularFireAuth,public navCtrl: NavController,) {
this.afAuth.authState.subscribe(user => {
if(user)
{
console.log('welcome')
}
else
{
this.navCtrl.push(LoginPage)
}
})
}
我正在使用ionic3和firebase
当我导航到onAuthStateChanged(firebase)函数中的登录页面时。 我的表单在登录页面中验证无效。 仅在从站点外导航此功能时有效。
home.ts
export class HomePage {
constructor(public afAuth:AngularFireAuth,public navCtrl: NavController,) {
this.afAuth.auth.onAuthStateChanged(user =>{
if(!user)
{
this.navCtrl.push(LoginPage
}
})
}
}
export class LoginPage {
loginForm: FormGroup;
constructor(public alertCtrl: AlertController,public fb: FormBuilder,public navCtrl: NavController,public afAuth: AngularFireAuth, public navParams: NavParams) {
this.createForm()
}
createForm() {
this.loginForm = this.fb.group({
'user': ['',Validators.compose([Validators.required]),],
'pass': ['', Validators.compose([Validators.required])],
});
}
showAlert() {
const alert = this.alertCtrl.create({
title: 'Something wrong',
subTitle: 'Wrong email or password',
buttons: ['OK']
});
alert.present();
}
login()
{
if(this.loginForm.valid)
{
var username = this.loginForm.get('user').value
var password = this.loginForm.get('pass').value
this.afAuth.auth.signInWithEmailAndPassword(username,password).catch((err)=>{
console.log(err)
this.showAlert()
})
}
}
login.html
<form [formGroup]="loginForm">
<p class="text-danger bg-dark p-2" *ngIf="loginForm.controls['user'].errors && !loginForm.controls['user'].pristine">required</p>
<input type="text" placeholder="Email" class="form-control input-style" formControlName="user">
<p class="text-danger bg-dark p-2" *ngIf="loginForm.controls['pass'].errors && !loginForm.controls['pass'].pristine">required</p>
<input type="text" placeholder="Password" formControlName="pass" class="form-control input-style">
</form>
<button type="submit" [disabled]="loginForm.invalid" (click)="login()" class="ghost-round full-width">Login</button>