mzingaye nkala
mzingaye nkala

Reputation: 27

Angular Observable unkown not assignable. using firebase

I am using Angular 8 to make a todo app with a firebase backend.

This is my todo service file which contains the error stating:

Type `Observable unknown[]` is not assignable to type `Observable ITodo[]`.

Type `unknown[]` is not assignable to type `ITodo[]`.

Type `{}` is missing the following properties from type `ITodo`: task, completed
import { AngularFireDatabase } from '@angular/fire/database';
import { Observable } from 'rxjs';
import { ITodo } from './models/todo';

@Injectable({
  providedIn: 'root'
})
export class TodosService {

  constructor(private db: AngularFireDatabase) { }

  createTodo() {
    return this.db.list('Todos').push({
      task: 'clean',
      completed: 'false'
    });
  }

  getTodo(): Observable<ITodo[]>{
    return this.db.list('Todos').valueChanges();
  }
}

My interface looks like this:

export interface ITodo {
    task:string,
    completed: boolean
}

Does any one have an idea why I am getting that error? Thanks note: the error is on my getTodo method.

Upvotes: 0

Views: 151

Answers (1)

Edric
Edric

Reputation: 26740

This is because you didn't specify a generic for the list method, which optionally accepts a type variable that you can type the result against.

The full definition of AngularFireDatabase#list is as follows:

list<T>(pathOrRef: PathReference, queryFn?: QueryFn): AngularFireList<T>;

And the definition for the AngularFireList interface, which accepts a type variable:

export interface AngularFireList<T> {
  query: DatabaseQuery;
  valueChanges(events?: ChildEvent[]): Observable<T[]>;
  snapshotChanges(events?: ChildEvent[]): Observable<SnapshotAction<T>[]>;
  stateChanges(events?: ChildEvent[]): Observable<SnapshotAction<T>>;
  auditTrail(events?: ChildEvent[]): Observable<SnapshotAction<T>[]>;
  update(item: FirebaseOperation, data: Partial<T>): Promise<void>;
  set(item: FirebaseOperation, data: T): Promise<void>;
  push(data: T): database.ThenableReference;
  remove(item?: FirebaseOperation): Promise<void>;
}

As such, you should add a type variable as follows:

getTodo(): Observable<ITodo[]>{
  return this.db.list<ITodo>('Todos').valueChanges();
}

It's also stated in the "Retrieving data as lists" documentation:

Data is retrieved through the AngularFireDatabase service. The service is also generic. Provide the singular type and not the array type.

const listRef = db.list('items');
const shirtsRef = db.list<Shirt>('shirts');

Upvotes: 1

Related Questions