Тип "AngularFireAction<DatabaseSnapshot <{} >> []" нельзя назначить типу "Product[]"
Итак, я следую этому курсу, который использует предыдущую версию (4.0) angularfire2, и я использую последнюю версию (5.0), и у меня возникла эта проблема с моим кодом.
Я получаю эту ошибку, что тип "AngularFireAction>[]" не может быть назначен типу "Product[]".
export class AdminProductsComponent implements OnInit, OnDestroy {
products: Product[];
filteredProducts: any[];
subscription: Subscription;
tableResource: DataTableResource<Product>;
items: Product[];
itemCount: number;
constructor(private productService: ProductService) {
this.subscription = this.productService.getAll().subscribe(products => {
this.filteredProducts = this.products = products;
this.initializeTable(products);
});
}
private initializeTable(products: Product[]){
this.tableResource = new DataTableResource(products);
this.tableResource.query({ offset: 0})
.then(items => this.items = items);
this.tableResource.count()
.then(count => this.itemCount = count);
}
reloadItems(params){
if(!this.tableResource) return;
this.tableResource.query(params)
.then(items => this.items = items);
}
filter(query: string){
this.filteredProducts = (query) ?
this.products.filter(p =>
p.title.toLowerCase().includes(query.toLowerCase())) :
this.products;
}
ngOnDestroy(){
this.subscription.unsubscribe();
}
}
Вот код продукта службы
export class ProductService {
constructor(private db: AngularFireDatabase) { }
create(product){
return this.db.list('/products').push(product);
}
getAll(){
return this.db.list('/products').snapshotChanges();
}
get(productId){
return this.db.object('/products/' + productId);
}
update(productId, product){
return this.db.object('/products/' + productId).update(product);
}
delete(productId){
return this.db.object('/products/' + productId).remove();
}
}
1 ответ
Решение
getAll()
метод в вашем сервисе возвращается snapshotChanges()
, это Observable<AngularFireAction<DatabaseSnapshot<{}>>[]>
и вы пытаетесь передать это initializeTable(products: Product[])
, Вот что говорит ошибка.
Чтобы решить эту проблему, вам необходимо отобразить .snapshotChanges()
на ваш Product[]
вот так:
getAll(): Observable<Product[]> {
return this.db.list<Product>('/products')
.snapshotChanges()
.pipe(
map(changes =>
changes.map(c => {
const data = c.payload.val() as Product;
const id = c.payload.key;
return { id, ...data };
})
)
);
}
GetAllProducts() : Observable<Product[]>{ returnthis.db.list('/products').snapshotChanges().pipe(
map(changes =>
changes.map(c => ({ key: c.payload.key, ...c.payload.val() as Product }))
)
);
}
Сначала вам следует добавить GetAll()
как указано выше, и вы должны добавить as Product
интерфейс в вашей функции.