Ionic Firebase Angular 异步验证

杰罗克

我正在尝试设置验证,因此如果用户名被占用,新用户将无法使用相同的用户名进行注册。我收到错误无法找到 afDatabase,这是在username.ts 中发生的它找不到在构造函数中定义的 FirebaseDatabase。为什么会这样?谢谢您的帮助。

无法读取未定义的属性“afDatabase”

用户名.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);
        }
    });
  }
}

profile-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. 尝试解决这个矛盾,看看是否能解决问题。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章