列出视图中的所有项目:
<ion-list>
<ion-item *ngFor="let item of arrData; let i = index" (click)="delete(item)">
{{i+1}}. {{item.name}}<small> - {{item.address}}</small>
</ion-item>
</ion-list>
在控制器中定义了数据库,因为显示和添加数据正在运行:
arrData = []
constructor(public navCtrl: NavController, private fdb: AngularFireDatabase) {
this.fdb.list("/schools/").valueChanges().subscribe(data =>{
this.arrData = data;
console.log(this.arrData);
})
btnAddClicked(){
this.fdb.list("/schools/").push({name:this.schoolName, address:this.schoolAddress});
}
我想在选中(点击)时删除项目。从文档中我了解到可以使用.remove(),只需要项目的路径。但为此我需要获得自动生成的密钥。怎么做到的?或者还有其他方法可以删除所选项目吗?
答案 0 :(得分:1)
感谢this帖子,找到了解决方案。也许不是最漂亮的,但有效:
delete(item){
var db = this.fdb.database.ref();
var query = this.fdb.database.ref("schools").orderByKey();
query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var pkey = childSnapshot.key;
var chval = childSnapshot.val();
//check if remove this child
if(chval.name == item.name && chval.address == item.address){
db.child("schools/"+pkey).remove();
return true;
}
});
});
}
答案 1 :(得分:0)
我认为您需要在代码中添加一些内容。我转到您的代码段以解决我的担忧。 chval = childSnapshot.val();行应该更改为带有括号的chval = childSnapshot.val。
deleteNote(key){
// var db = this.fdb.database.ref();
var query = firebase.database().ref('todo').orderByKey();
query.once("value")
.then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
var pkey = childSnapshot.key;
var chval = childSnapshot.val;
console.log(childSnapshot.val);
//check if remove this child
if(chval.note == key.note && chval.date == key.date){
firebase.database().ref().child("todo/"+pkey).remove();
return true;
}
});
});
this.state.noteArray.splice(key, 1);
this.setState({noteArray: this.state.noteArray});
}