tunneling
tunneling

Reputation: 527

Angular + Firebase: Assign Observable<Object[]> to MatTableDataSouce<Object>

I have a list component with a MatTableDataSource where I'm trying to wire it to a collection from AngularFireStore. I've followed a few tutorials where accessing the "payload" was in the component. I'm attempting to isolate the component from firebase specifcs in case I decide to change the backend later. I've broken my app.

Also, in general this code this works, but the error annoys me and the sorting and pagination are broken.

I get the following error:

Type 'Observable<Cart[]>' is missing the following properties from type 
'MatTableDataSource<Cart>':_data, _renderData, _filter, _internalPageChanges, and 18 more.

In the Cart Service, I have the following class defintion and constructor (the rest of the code is just CRUD stuff):

export class CartService {
  private cartCollection: AngularFirestoreCollection<Cart>;
  carts: Observable<Cart[]>;
  private cartDoc: AngularFirestoreDocument<Cart>;

  constructor(public db: AngularFirestore) {
    this.cartCollection = db.collection<Cart>('carts');
    this.carts = this.cartCollection.snapshotChanges().pipe(
      map(actions => actions.map(a => {
        const data = a.payload.doc.data() as Cart;
        const id = a.payload.doc.id;
        return { id, ...data };
      }))
    );
  }

....

In the Cart List component, I'm doing...

export class CartListComponent implements OnInit, AfterViewInit {
   public filteredCarts = new MatTableDataSource<Cart>();

...

then,

...
ngOnInit() {
  this.filteredCarts = this.service.carts; \\<- error lives here
}
...

Upvotes: 1

Views: 80

Answers (1)

anexo
anexo

Reputation: 505

In the direction @Powkachu points in his comment: you are mixing datatypes and also, you may not be subscribed to the service return. Try something like:

ngOnInit() {
    this.service.carts()
    .subscribe(res => {
      const data: Cart[] = res;
      this.filteredCarts = new MatTableDataSource<Cart>(data);
    });
  }

Upvotes: 1

Related Questions