【问题标题】:firebase update value of a key in Angular 2(Version 5)Angular 2(版本5)中键的firebase更新值
【发布时间】:2018-12-17 11:25:51
【问题描述】:

当我将数据(使用 push() 方法)插入 firebase 时,它​​会生成一个随机密钥,如图所示。我可以使用随机数更新键值(姓名和年龄)(-LExEhDWjw​​Xcj6rGZar9)

现在我想要实现的是,我想在不使用 **-LExEhDWjw​​Xcj6rGZar9 的情况下更新键值(name:"Manjeshwar" age:"27" 为 name:"somename" age:"20") /strong> 随机键**。我想动态更新它。

【问题讨论】:

  • 不知道key怎么知道要更新哪个节点?
  • 谢谢您的回复。我将向您澄清我的问题,我正在 angular2 中创建一个表单,员工可以在其中创建他们的个人资料并根据需要进行更新。当他们创建一个随机密钥时会生成。那么如何获取更新密钥呢? angular2中是否有可用的getkey方法?

标签: angular typescript firebase-realtime-database angular5


【解决方案1】:

经过大量研究,我得到了自己问题的答案。 答案:要获取密钥,只需在 Angular2 中使用 "$key",这样您就可以更新任何要更新的随机密钥的值,如下面的代码所示。

组件.html:

    <div class="employees" *ngFor="let e of employees | async">
        <ul>
                <li>Name: {{e.name }}</li>
                <li>Age: {{e.age}}</li>
                <li>Random Key: {{e.$key }}</li> //outputs random key
                <button class="btn btn-primary" (click)="goToDetails(e, '$key')">Edit</button>
        </ul>

    </div>
//form to update the values
<div id="uform" class="col-md-4" hidden>
    <input class="form-control col-md-3" type="text" placeholder="Name" id="uname"  name="name">
    <input class="form-control col-md-3" type="number" placeholder="Age" id="uage"   age = "age">

    <button class="btn btn-primary" (click) = update()>Update</button>
</div>

组件.ts:

  //Function to get id of form
  getInputVal(id){
    return (<HTMLInputElement>document.getElementById(id)).value;
  }

  fbkey:string = ''; //global variable

   goToDetails(employees:{},key:string) {
    this.fbkey = employees[key];  
    document.getElementById("uform").style.display = "block";
  }
  update(){
    //Get Values
    var name =this.getInputVal('uname');
    var age= this.getInputVal('uage');
    this.updateF(name, age);
  }

  updateF(name, age){
    this.af.database.object('employees/'+this.fbkey).set({
      name: name,
      age: age

    })
  }

所以使用 "$key" 我们可以动态更新特定键的值。

【讨论】:

    【解决方案2】:

    要获得密钥,您必须知道该密钥下的某些内容。假设您知道用户的名称,那么您可以查询具有该名称的所有用户并更新它们:

    var ref = firebase.database().ref("employees");
    ref.orderByChild("name").equalTo("manjeshwar s").once("value", function(snapshot) {
      snapshot.forEach(function(employee) {
        employee.ref.update({ age: "20" });
      });
    });
    

    请注意,如果有多个同名员工,所有员工都会更新。

    如果员工姓名是唯一的,请考虑实际将其用作每个员工节点的键:

    employees
      "manjeshwar s": {
        ...
      }
      "puf": {
        ...
      }
    

    使用这种结构,您可以保证员工姓名是唯一的。您无需查询即可更新它们:

    ref.child("manjeshwar s").update({ age: "20" });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-01
      • 1970-01-01
      • 2019-02-04
      • 1970-01-01
      • 2018-05-25
      • 1970-01-01
      • 2017-01-24
      • 1970-01-01
      相关资源
      最近更新 更多