Description
Version info
Angular: 11
Firebase: 8
AngularFire: 6
Other: MacOS Big Sur
Issue
When you call valueChanges on a document you know doesn't exist, it emits undefined. However if you specify idField, for example, as id, then it will return an object with the field id. I expected that it would still return undefined. It returning causes problems, as the object then isn't in the shape you expect (if you specify a type of the result) but also you get a result when a document doesn't actually exist.
I think the issue is simply in the valueChanges function:
valueChanges<K extends string>(options: { idField?: K } = {}): Observable<T | undefined> {
return this.snapshotChanges().pipe(
map(({ payload }) =>
options.idField ? {
...payload.data(),
...{ [options.idField]: payload.id }
} as T & { [T in K]: string } : payload.data()
)
);
}
As you can see, if payload.data() is undefined, this function will create an object with id field. I think a simple fix would be:
valueChanges<K extends string>(options: { idField?: K } = {}): Observable<T | undefined> {
return this.snapshotChanges().pipe(
map(({ payload }) =>
options.idField && payload.data() ? {
...payload.data(),
...{ [options.idField]: payload.id }
} as T & { [T in K]: string } : payload.data()
)
);
}
I don't actually know much about the underlying firebase apis, but I'm assuming that payload.data() is undefined if there is no document.