首页 > 解决方案 > 从 Firestore 数据创建单选按钮警报

问题描述

我想通过使用 fireStore 中的数据创建一个单选按钮警报。我通过 valueChanges() 生成了一个 observable,但是当我在无法读取数据并最终无法插入单选按钮的值的函数中使用它时,console.log 返回 Undefined。我是 fireStore 和 ionic 的新手。

我也尝试过使用 .get().then(function(doc) 但返回错误不是函数。我也尝试过使用 subscribe() 但也无法给我实际数据,或者我错过了一些东西。我google了很多天,就是找不到解决办法,希望有人能帮忙。

myMemberList = [];

constructor(public navCtrl: NavController, 
       public alertCtrl: AlertController,
       public firestore: AngularFirestore, 
       public afAuth: AngularFireAuth,
    ) { }

ionViewDidEnter() {
  this.afAuth.authState.subscribe(user => {
     if (user) {
      this.userId = user.uid;
      this.fireStoreTaskList = this.firestore.doc<any>('users/' + 
      this.userId).collection('Member').valueChanges();
     }
  });
}

// create the inputs for radio button //
createInputs() {
    const theNewInputs = [];
 for (let i = 0; i < this.fireStoreTaskList.length; i++) { // undefined
    theNewInputs.push(
      {
        type: 'radio',
        label: this.fireStoreTaskList.memberName,     // undefined
        value: this.fireStoreTaskList.memberId,       // undefined
        checked: false      
      }
    );

  } {
  console.log(theNewInputs);
  }
  return theNewBeneInputs;
}

// Radio button alert to choose data //
async selectMember() {
  this.myMemberList = this.createInputs();
  const alert = await this.alertCtrl.create({
    header: 'Member',
    inputs: this.myMemberList,

    buttons: [{ text: 'Cancel', role: 'cancel' },
              { text: 'OK',
                 handler: data => {
                 console.log(data)
                }
              }
              ]
  });
  await alert.present();
}

标签: ionic-frameworkgoogle-cloud-firestore

解决方案


我使用 Ionic 4 已经有一段时间了,我还在我的应用程序中集成了 Firebase Firestore。我并没有真正理解整个描述,但我有一个解决方案可以解决您最初的问题“我想通过使用 Firestore 中的数据来创建单选按钮警报”

我假设您已经使用 Firebase 应用程序设置了您的应用程序,如果没有,那么我建议您遵循如何使用 Firebase 和 AngularFire 5 构建 Ionic 4 应用程序

我的示例有 1 个按钮,每当您单击它时,它将执行以下操作:

  1. 访问 Firestore 数据库。
  2. 下载 Firestore 文档。
  3. 获取每个文档的字段memberName
  4. 将这些名称添加到名称数组中
  5. 创建单选按钮警报。
  6. 对于单选按钮,它将创建一个包含成员名称的单选按钮列表。
  7. 显示数组。

为了使我的代码正常工作,这是我遵循的 Firestore 数据库结构:

.
└── collection: "users"
    └── document: "autogenerated_id"
    |   ├── memberID: "user_id"
    |   └── memberName: "Name 01"
    └── document: "autogenerated_id"
        ├── memberID: "user_id"
        └── memberName: "Name 02"

单击按钮时,您将看到带有单选按钮的警报,例如名称 01名称 02

正如我上面提到的,这是我的示例代码。如您在问题中所述,它从 Firestore 加载数据使用该数据创建带有单选按钮的警报。我在代码中为你添加了很多注释。如果这不是您正在寻找的内容,请查看代码并根据您的需要进行修改。


推荐阅读