【问题标题】:Ionic Firebase Angular Async validationIonic Firebase Angular 异步验证
【发布时间】:2018-01-14 14:04:47
【问题描述】:

我正在尝试设置验证,因此如果使用用户名,新用户将无法使用相同的用户名注册。我收到一个错误,无法找到在 username.ts 中发生的 afDatabase。它找不到构造函数中定义的 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();
    }
  }
}

【问题讨论】:

    标签: angular typescript firebase


    【解决方案1】:

    在您的UsernameValidator 类中,您将checkUsername 方法定义为static,这意味着它不能绑定到该类的特定实例。但是,您在此方法中使用了this.afDatabase,它必须来自该类的特定实例。

    因此,您对checkUsername 的实现与您将其定义为static 的事实相矛盾。尝试解决这个矛盾,看看是否能解决问题。

    【讨论】:

      猜你喜欢
      • 2019-03-12
      • 2020-03-06
      • 2018-02-15
      • 2017-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-20
      相关资源
      最近更新 更多