【问题标题】:Update specific field of all user firebase angular更新所有用户 firebase 角度的特定字段
【发布时间】:2021-12-01 12:47:45
【问题描述】:

由于我是 Angular 和 Ionic 的新手,我正在尝试更新用户的特定字段。我想显示来自 firebase 的所有数据并只更新一个字段。 我只能为一个登录的用户做,但不能为所有用户做。

export class AdminPage implements OnInit {
user:any;
userId:string;
enableAccess:boolean;
  constructor(
    private auth:AuthService, 
    private router:Router, 
    private afs:AngularFirestore,
    private loadingCtrl:LoadingController,
    private toastr:ToastController) { }

  ngOnInit() {
    this.auth.getAllUser().subscribe(user=>{
      this.user=user;
    })
    this.auth.user$.subscribe(user=>{
      this.enableAccess=user.IsApproved;
    })
    
  }
  async updateUserInfo(){
    const loading=await this.loadingCtrl.create({
      message:'updating',
      spinner:'crescent',
      showBackdrop:true
    })
    loading.present()
    this.afs.collection('user').doc(this.userId).set({
      'IsApproved':this.user.enableAccess
    },{merge:true}).then(()=>{
      this.toast('update sucessful','success');
    }).catch(error=>{
      loading.dismiss();
      this.toast(error.message,'danger');
    })
  }
  async toast(message,status){
    const toast =await this.toastr.create({
      message:message,
      color: status,
      position: 'top',
      duration:2000
    });
  }
}

组件

ion-content>
  <ion-card>
      <ion-item> 
        <ion-label position="floating">Email:</ion-label>
        <p></p>
      </ion-item>

      <ion-item>
        <ion-label position="floating">Enable Access:</ion-label>
        <ion-input
          required
          type="boolean"
          [(ngModel)]="enableAccess"
          name="enableAccess"
        ></ion-input>
      </ion-item>
      <ion-button
        type="submit"
        expand="block"
        shape="round"
        (click)="updateUserInfo()"
        >Update</ion-button
      >

  </ion-card>
</ion-content>

我想显示数据库中每个用户的电子邮件,并且我想允许管理员仅更新 enableAccess 字段。如何获取所有用户并更新字段?

【问题讨论】:

    标签: angular typescript firebase ionic-framework google-cloud-firestore


    【解决方案1】:

    听起来您正在尝试为现有用户回填一些数据。如果是这种情况,我建议使用一次性 node.js 脚本来执行此操作,而不是在客户端应用程序代码中。

    在 node.js 中这看起来像:

    const admin = require("firebase-admin");
    admin.initializeApp(...);
    
    const db = admin.firestore();
    db.collection("user").get((snapshot) => {
      snapshot.forEach((doc) => {
        doc.ref.update({ IsApproved: false });
      });
    });
    

    如果您坚持在客户端代码中执行此操作,则几乎相同。鉴于这不会立即影响 UI,我建议通过常规 SDK 在 JavaScript 中进行回填。

    即使结果显示在 Angular UI 中,AngularFire 也是构建在 JavaScript SDK 之上的,因此它们可以完美地互操作。这意味着更新也将立即显示在 AngularFire 中,即使您通过(更简单的)JavaScript SDK 进行更新也是如此。

    【讨论】:

      猜你喜欢
      • 2017-11-30
      • 2019-03-12
      • 2018-09-28
      • 1970-01-01
      • 2017-09-10
      • 2015-11-16
      • 1970-01-01
      • 2021-11-29
      • 2021-11-16
      相关资源
      最近更新 更多