0

I'm using material 2, and I'm trying to create data tables with pagination and sorting, so I need my collections to be observable, but I think I must be populating/initialising the arrays incorrectly in the controller.

I've been populating an 'expenses' array with data from an 'expenses' firestore collection using the method below, but this always says "Type 'Observable<{}[]>' is not assignable to type 'any[]'"...

import { Component, OnInit, AfterViewInit, ViewChild } from '@angular/core';

import { MatPaginator, MatTableDataSource, MatSort } from '@angular/material';

import { Observable } from 'rxjs/Observable';

import { AngularFireDatabase } from 'angularfire2/database';

import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';

@Component({
  selector: 'app-expense-list',
  templateUrl: './expense-list.component.html',
  styleUrls: ['./expense-list.component.scss']
})

export class ExpenseListComponent implements OnInit, AfterViewInit {

  tableColumns = [ 'id' ];

  expenses: any[];

  constructor(private db: AngularFirestore) {
    this.expenses = this.db.collection('/expenses').valueChanges();
  }

  ngOnInit() {

  }

  ngAfterViewInit() {

  }

  viewExpense(row) {
    console.log('viewExpense(' + row.id + '): ', row);
  }

}

How do I properly create an observable array that's populated with data from a firestore collection?

1
  • Hi, if you've found an answer to your question in the responses here, please consider accepting the answer by clicking the green check mark on the left. That way, other people will know that your question has been answered. No worries if you don't feel my answer answered your question, just wanted to let you know about the functionality. Tip: if you found a different / better way, you can always add your own answer. Welcome to SO :) Commented Feb 22, 2018 at 19:56

1 Answer 1

1

It's just a typing issue. If you change the type of expenses to Observable<any[]> your code will compile.

Basically, you told Typescript that you would be saving a plain Array of anything in the expenses property, but you are actually saving an Observable containing an Array (Obsevable<Array<any>> or Observable<any[]>).

Learn more about generic types here: https://www.typescriptlang.org/docs/handbook/generics.html.

Sign up to request clarification or add additional context in comments.

1 Comment

I've actually tried this repeatedly before, but it used to come up with another error, which made it look like adding Observable to any[] for firestore collections wasn't valid. Now I've tried it again with you suggesting this, clearly meaning I wasn't thinking wrong, and it's working.... Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.