[英]Ionic Firebase Angular Async validation
我正在嘗試設置驗證,以便如果使用用戶名,則新用戶無法使用相同的用戶名進行注冊。 我發現了一個錯誤無法找到afDatabase這在username.ts發生。 它找不到在構造函數中定義的FirebaseDatabase。 為什么會這樣呢? 謝謝您的幫助。
無法讀取未定義的屬性“ afDatabase”
username.ts
import { FormControl } from '@angular/forms';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFireDatabase } from 'angularfire2/database';
export class UsernameValidator {
constructor(private afAuth: AngularFireAuth, private afDatabase: AngularFireDatabase) {
}
static checkUsername(control: FormControl): any {
return new Promise(resolve => {
if(this.afDatabase.orderByChild('username').equals(control.value)){
resolve({
"username taken": true
});
}else{
resolve(null);
}
});
}
}
型材setup.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, ToastController } from 'ionic-angular';
import { FormBuilder, FormGroup, Validators} from '@angular/forms';
import { AngularFireAuth } from 'angularfire2/auth';
import { AngularFireDatabase } from 'angularfire2/database';
import { Profile } from './../../models/profile';
import { UsernameValidator } from '../../validators/username';
@IonicPage()
@Component({
selector: 'page-profile-setup',
templateUrl: 'profile-setup.html',
})
export class ProfileSetupPage {
profile = {} as Profile;
profileForm: FormGroup;
constructor(private afAuth: AngularFireAuth, private afDatabase: AngularFireDatabase, public navCtrl: NavController,
public navParams: NavParams, public formBuilder: FormBuilder, public toastCtrl: ToastController) {
this.profileForm = formBuilder.group({
username: ['', Validators.compose([Validators.required]), UsernameValidator.checkUsername]
});
}
createProfile(){
if(this.profileForm.valid){
this.afAuth.authState.take(1).subscribe(auth => {
this.afDatabase.object(`profile/${auth.uid}`).set(this.profile)
.then(() => this.navCtrl.setRoot('TabsPage'))
})
}else if (!this.profileForm.controls.username.valid){
let toast = this.toastCtrl.create({
message: 'Invalid Username',
duration: 3000,
position: 'bottom'
});
toast.present();
}
}
}
在UsernameValidator
類中,您已將checkUsername
方法定義為static
,這意味着它無法與該類的特定實例綁定。 但是,您在此方法內部使用this.afDatabase
,它必須來自類的特定實例。
因此,您的checkUsername
實現與將其定義為static
的事實相矛盾。 嘗試解決此矛盾,看看是否可以解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.