我正在尝试使用删除按钮显示事件列表,并且只能由事件创建者删除。但是当我尝试删除它时,它会删除所有其他事件。我实际上是在尝试从Firebase-realtime-database中通过键值删除,但是event.id
返回未定义,我想它会删除整个文件夹。
我的home.html,显示数据,可以直接从此页面删除
<ion-card *ngFor="let event of eventList$ | async">
<ion-item>
<h4>{{event.name}}</h4>
</ion-item>
<ion-item>
<h4>{{event.location}}</h4>
<ion-buttons end>
<button ion-button icon-only (click)="checkUser(event)">
<ion-icon name="trash"></ion-icon>
</button>
</ion-buttons>
</ion-item>
</ion-card>
我的home.ts
this.database.list<EventModels>('event-list').valueChanges().subscribe((eventData) => {
}, (err)=>{
console.log("Error while retrieving event details : ", err);
});
this.eventListRef$ = this.database.list<EventModels>('event-list');
this.eventList$ = this.eventListRef$.valueChanges();
checkUser(event: EventModels) {
console.log(event.id, event.name);
if(firebase.auth().currentUser.email == event.creator) {
let alert = this.alertCtrl.create({
title: 'Confirm Delete.',
message: 'You cannot recover this event once it is deleted.',
buttons: [
{
text: 'Yes',
role: 'destructive',
handler: () => {
this.eventListRef$.remove(event.id);
}
},
{
text: 'Cancel',
role: 'cancel'
}
]
}).present();
} else{
let alert = this.alertCtrl.create({
title: 'Could Not Delete Event!',
subTitle: 'This event does not belong to you.',
buttons: ['Dismiss']
});
alert.present();
}
}
我的EventModels,models文件夹中的events.ts
export interface EventModels {
id?: string;
creator: any;
name: string;
location: string;
start: any;
end: any;
time: any;
}
我尝试使用$key?: String
,但仍返回未定义
创建活动
addEvent = {} as EventModels;
eventRef$: AngularFireList<EventModels>;
this.eventRef$ = this.database.list('event-list');
save(addEvent: EventModels){
this.eventRef$.push({
creator: firebase.auth().currentUser.email,
name: this.addEvent.name,
location: this.addEvent.location,
start: this.addEvent.start,
end: this.addEvent.end,
time: this.addEvent.time,
});
this.addEvent = {} as EventModels;
this.navCtrl.pop()
}
答案 0 :(得分:1)
尝试更改eventList$
中home.ts
的创建方式,而不是使用snapshotChanges()提取每个项目的key
并分配给id
属性:< / p>
// ...
import { map } from 'rxjs/operators';
// ...
this.eventListRef$ = this.database.list<EventModels>('event-list');
this.eventList$ = this.eventListRef$.snapshotChanges()
.pipe(
map(changes =>
changes.map(c => ({ id: c.payload.key, ...c.payload.val() }))
)
);
id
可能不是您的event-list
RTDB节点中每个孩子都拥有的属性。 snapshotChanges()
公开每个对象的元数据,例如key
以及可用于为每个项目创建完整的EventModels
对象的对象值。
希望有帮助!