angular - 键入'AngularFireAction>[]' 不可分配给类型 'Product[]'
问题描述
所以我正在学习这门课程,它使用的是 angularfire2 的先前版本(4.0),我使用的是最新版本(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();
}
}
解决方案
您的服务中的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 };
})
)
);
}
推荐阅读
- javascript - 将表格列 DB 结果文本复制到剪贴板
- sql - SQL Mail 仅向查询中指定的用户发送电子邮件
- python - 有哪些选项可以缩短重复的 Python 代码?
- java - 为什么 StringBuffer 返回一个引用?
- javascript - 前端只删除数组中的最后一项
- docker - JIB docker hub 图像推送失败 com.fasterxml.jackson.core.JsonParseException:意外字符('<'(代码 60)):预期有效值
- python - 只要它们具有相同的索引,如何从另一个列表中减去一个列表中的数字?(Python)
- freeradius - 如何向 Access-Accept FreeRadius 添加新属性
- c# - C# PDFsharp 输出 RTF 文本
- windows - Corda 节点终端不从运行节点开始(Windows 10)