Angular FIrebase 5对象键未显示.所以不能删除 [英] Angular FIrebase 5 objects keys not being displayed. So can't delete
问题描述
问题已经回答,但我正在寻找一个(可能的)更简单的问题.只是为了访问对象键,我们不必实现一个而是两个映射就显得很奇怪.
The question has been answered but I'm looking for a, um, more straightforward one if available. It seems strange that we'd have to implement not one but two mappings just to have access to the object keys.
基本的Firebase数据库: 可以看出,课程对象显然具有键. 标记:
basic firebase db: As can be seen, the course objects clearly have keys. Mark-up:
<ul>
<li *ngFor="let course of courses$ | async">
<b>Key:</b> {{course.$key}} <!-- doesn't show --!>
<b>Title:</b> {{course.Title}}
<b>Duration:</b> {{course.Duration}}
<b>Author:</b> {{course.Author}}
<p><button (click)="deleteCourse(course)">Remove</button></p>
<hr>
</li>
</ul>
现在,课程显示得很好,但是我不知道如何删除该键. (或者也许我没有在我的firebaseDatabase对象上使用正确的方法).无论哪种方式,当我在控制台中登录密钥时,它都显示为未定义.
Now, the courses display just fine, but I don't know how to get a reference to the key in order to delete it. (Or perhaps I'm not using the right method on my firebaseDatabase Object). Either way, when I log the key in the console, it shows as undefined.
export class AppComponent {
courses;
courses$: AngularFireList<any>;
constructor(private db: AngularFireDatabase) {
this.courses = db.list('/courses');
this.courses$ = this.courses.valueChanges();
}
...
deleteCourse(course) {
console.log(course.$key); // -> undefined
this.db.object('/courses/' + course.$key).remove();
}
}
推荐答案
更新后的答案
Rxjs改变了其管道数据传输方式.现在您必须使用.pipe()
.
Rxjs have changed how it pipes data. now you have to use .pipe()
.
this.courses$ = this.courses.snapshotChanges().pipe(
map(changes =>
changes.map(c => ({ key: c.payload.key, ...c.payload.val() }))
)
);
原始答案
.valueChanges()
仅包含数据,不包含任何键.您需要使用.snapshotChanges()
.valueChanges()
contain simply data, no key with it. you need to use .snapshotChanges()
this.courses$ = this.courses.snapshotChanges().map(changes => {
return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
});
现在只需使用{{course.key}}
这是您的更正代码
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
export class AppComponent {
courseRef: AngularFireList<any>;
courses$: Observable<any[]>;
constructor(private db: AngularFireDatabase) {
this.courseRef = db.list('/courses');
this.courses$ = this.courseRef.snapshotChanges().map(changes => {
return changes.map(c => ({ key: c.payload.key, ...c.payload.val()
}));
});
}
...
deleteCourse(course) {
console.log(course.key);
this.db.object('/courses/' + course.key).remove();
}
}
这篇关于Angular FIrebase 5对象键未显示.所以不能删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!