I'm using firebase in my application. So, the snapshotChanges() method of firebase returning an Observable of type SnapshotAction array which I want to convert to specific type array after subscribing to an Observable. So, how can we do this in typescript?
Have a look at codebase below to understand it better,
// Below observable is returned by firebase snapshotChanges() method Observable<SnapshotAction<Product>[]> // Now, after I subscribe to the above observable I get below type, SnapshotAction<Product>[] // Now I want to convert "SnapshotAction<Product>[]" to "Product[]" in typescript
Snapshot action has a payload field which will give you a
DatabaseSnapshot<Product>
A DatabaseSnapshot has a val() method which will return a Product or null depending if the snapshot exists. So you can write a small function like this to extract the product:
function example(input: SnapshotAction<string>[]): (string | null)[] {
return input.map(action => action.payload.val())
}
Note that this is return string | null because the snapshot might not exist. You could look at
action.payload.exists()
If you want to do additional checks or filtering.
products: Product[] = []; this.productService.getAll().pipe( switchMap((products: SnapshotAction<Product>[]) => { // Our intention starts here products.map(product => { let prod: Product = product.payload.val(); prod.key = product.key; this.products.push(prod); }); }); );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.