Search code examples
angularfirebaseangularfire2angularfire

Type 'AngularFireAction<DatabaseSnapshot<{}>>[]' is not assignable to type 'Product[]'


So i am following this course which is using the previous version(4.0) of angularfire2 and I am using the latest version(5.0) and I am having this issue with my code.

An I am getting this error that Type 'AngularFireAction>[]' is not assignable to type 'Product[]'.

export class AdminProductsComponent implements OnInit, OnDestroy {
products: Product[];
filteredProducts: any[];
subscription: Subscription;
tableResource: DataTableResource<Product>;
items: Product[];
itemCount: number;

constructor(private productService: ProductService) {
 this.subscription = this.productService.getAll().subscribe(products => {
  this.filteredProducts = this.products = products;
  this.initializeTable(products);
 });

}

private initializeTable(products: Product[]){
 this.tableResource = new DataTableResource(products);
  this.tableResource.query({ offset: 0})
    .then(items => this.items = items);
  this.tableResource.count()
    .then(count => this.itemCount = count);
}

reloadItems(params){ 
 if(!this.tableResource) return;
 this.tableResource.query(params)
    .then(items => this.items = items);
}

filter(query: string){
   this.filteredProducts = (query) ?
   this.products.filter(p => 
   p.title.toLowerCase().includes(query.toLowerCase())) :
   this.products; 
}

ngOnDestroy(){
  this.subscription.unsubscribe();
}


}

Here is the code of product service

export class ProductService {

constructor(private db: AngularFireDatabase) { }

create(product){
  return this.db.list('/products').push(product);
}

getAll(){
  return this.db.list('/products').snapshotChanges(); 
}

get(productId){
  return this.db.object('/products/' + productId);
}

update(productId, product){
  return this.db.object('/products/' + productId).update(product);
}

delete(productId){
  return this.db.object('/products/' + productId).remove(); 
}

}


Solution

  • The getAll() method in your service is returning snapshotChanges(). this is an Observable<AngularFireAction<DatabaseSnapshot<{}>>[]> and you are trying to pass this to initializeTable(products: Product[]). That is what the error is saying.

    In order to solve this, you need to map the .snapshotChanges() to your Product[] like so:

    getAll(): Observable<Product[]> {
        return this.db.list<Product>('/products')
            .snapshotChanges()
            .pipe(
                map(changes =>
                    changes.map(c => {
                        const data = c.payload.val() as Product;
                        const id = c.payload.key;
                        return { id, ...data };
                    })
                )
            );
    }