我有一个Angular 8应用程序并使用firebase。我想从服务中检索数据。所以我做了一个检索数据的功能。但是我在该函数上遇到了错误
我在Google上搜索了很多内容,并阅读了Firebase文档。但这并没有解决问题。
这就是我所拥有的功能:
findCourseByUrl(courseUrl: string): Observable<Course> {
return this.db.list('courses', ref => {
return ref.orderByChild('url').equalTo(courseUrl);
}).snapshotChanges().pipe(map(data => data[0]));
}
但是我仍然收到此错误:
Type 'Observable<AngularFireAction<DatabaseSnapshot<unknown>>>' is not assignable to type 'Observable<Course>'.
Type 'AngularFireAction<DatabaseSnapshot<unknown>>' is missing the following properties from type 'Course': id, url
如果我这样做:
findCourseByUrl(courseUrl: string): Observable<Course> {
return this.db.list('courses', ref => {
return ref.orderByChild('url').equalTo(courseUrl);
}).snapshotChanges().pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Course;
return { ...data };
});
}));
}
然后我将收到此错误:
Property 'doc' does not exist on type 'DatabaseSnapshot<unknown>'.
Property 'doc' does not exist on type 'DatabaseSnapshotExists<unknown>'.ts(2339)
Type 'Observable<{ id: string; url: string; description: string; iconUrl: string; courseListIcon: string; longDescription: string; }[]>' is not assignable to type 'Observable<Course>'.
Type '{ id: string; url: string; description: string; iconUrl: string; courseListIcon: string; longDescription: string; }[]' is missing the following properties from type 'Course': id, url, description, iconUrl, and 2 more.ts(2322)
这是模型:
export interface Course {
id: string;
url: string;
description: string;
iconUrl: string;
courseListIcon: string;
longDescription: string;
}
答案 0 :(得分:2)
尝试像这样更改代码:
findCourseByUrl(courseUrl: string): Observable<Course> {
return this.db.object('courses', ref => {
return ref.equalTo(courseUrl);
}).snapshotChanges().pipe(
map(actions => {
return actions.map(a => {
const data = a.payload.val() as Course;
const id = a.payload.key;
return { id, ...data };
});
}));
}
编辑
上面的代码是单个对象和对象列表的混合体,因此不起作用。以下代码用于获取单个对象。
findCourseByUrl(courseUrl: string): Observable<Course> {
return this.db.object(`courses/${courseUrl}`).snapshotChanges().pipe(
map(a => {
const data = a.payload.val() as Course;
const id = a.payload.key;
return { id, ...data };
});
}