Rextrem 8
Rextrem 8

Reputation: 51

Type 'Observable<DocumentData[]>' is not assignable

I'm new to angular and to firebase and I try to do a simple program using the example of the angular/fire library:

import { Component } from '@angular/core';
import { Firestore, collectionData, collection } from '@angular/fire/firestore';
import { Observable } from 'rxjs';

interface Item {
  name: string
};

@Component({
  selector: 'app-root',
  template: `
  <ul>
    <li *ngFor="let item of item$ | async">
      {{ item.name }}
    </li>
  </ul>
  `
})
export class AppComponent {
  title = 'firetest2812';
  item$: Observable<Item[]>;
  constructor(firestore: Firestore) {
    const collect = collection(firestore, 'items');
    this.item$ = collectionData(collect);
  }
}

While compiling I got these error: " Error: src/app/app.component.ts:24:5 - error TS2322: Type 'Observable<DocumentData[]>' is not assignable to type 'Observable<Item[]>'. "

Can someone tell me what's wrong please? Thanks!

Upvotes: 5

Views: 1456

Answers (3)

Jules le dev
Jules le dev

Reputation: 49

I solved this by casting like this :

 this.item$ = collectionData(collect) as Observable<Item[]>

Or in a good way

You can use AngularFirestore as firestore type instead of Firestore

You will get something like this

import {Component} from '@angular/core';
import {Observable} from "rxjs";
import {AngularFirestore} from "@angular/fire/compat/firestore";


interface Item {
  name: string
}

@Component({
  selector: 'app-root',
  template: `
    <ul>
      <li *ngFor="let item of item$ | async">
        {{ item.name }}
      </li>
    </ul>
  `
})
export class AppComponent {
  title = 'firetest2812';
  item$: Observable<Item[]>;

  constructor(firestore: AngularFirestore) {
    this.item$ = firestore.collection<Item>("items").valueChanges();

  }
}

Upvotes: 5

David East
David East

Reputation: 32604

You need to provide the generic type in the collectionData() function since you specified the item$ Observable type as Item[] in the property.

export class AppComponent {
  title = 'firetest2812';
  item$: Observable<Item[]>;
  constructor(firestore: Firestore) {
    const collect = collection(firestore, 'items');
    // Specify the type here
    this.item$ = collectionData<Item>(collect);
  }
}

Alternatively, the lazy answer is do use any.

export class AppComponent {
  title = 'firetest2812';
  item$: Observable<any[]>;
  constructor(firestore: Firestore) {
    const collect = collection(firestore, 'items');
    // Specify the type here
    this.item$ = collectionData(collect);
  }
}

Upvotes: 0

Lukasz Gawrys
Lukasz Gawrys

Reputation: 1334

You have to pass your interface as type to the collection function.

 const collect = collection<Item>(firestore, 'items');

Upvotes: 0

Related Questions