Reputation: 3949
I have a Angular 8 application and using firebase. I want to retrive data from a service. So I made a function for retrieving the data. But I get an error on that function
I googled a lot and read the firebase documentation. But it didnt fixed the problem.
So this is the function I have:
findCourseByUrl(courseUrl: string): Observable<Course> {
return this.db.list('courses', ref => {
return ref.orderByChild('url').equalTo(courseUrl);
}).snapshotChanges().pipe(map(data => data[0]));
}
But I still get this error:
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
If I do this:
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 };
});
}));
}
I will then get this error:
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)
This is the model:
export interface Course {
id: string;
url: string;
description: string;
iconUrl: string;
courseListIcon: string;
longDescription: string;
}
Upvotes: 1
Views: 790
Reputation: 5835
Try to change your code like this:
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 };
});
}));
}
EDIT
The code above is a mixture for single objects and list of objects, so it's not working. The following code is for a single object to get.
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 };
});
}
Upvotes: 2