因此,我正在按照本课程使用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();
}
}
答案 0 :(得分: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 };
})
)
);
}
答案 1 :(得分:0)
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
接口。