Reputation: 51
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
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
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
Reputation: 1334
You have to pass your interface as type to the collection
function.
const collect = collection<Item>(firestore, 'items');
Upvotes: 0