【发布时间】:2020-06-24 07:58:44
【问题描述】:
在我使用最新版本时遵循 Angular 4 制作的课程,但我终生无法解决这个问题。
尝试过滤产品时,products.component.ts 出现错误。
任何帮助将不胜感激,我还是新手,这是我学习 Angular 的第四天。
Type 'unknown[]' is not assignable to type 'Product[]'.
Type '{}' is missing the following properties from type 'Product': title, price, category, imageUrl
product.ts
export interface Product {
title: string;
price: number;
category: string;
imageUrl: string;
}
product.service.ts
import { map } from 'rxjs/operators';
import { AngularFireDatabase } from 'angularfire2/database';
import { Injectable } from '@angular/core';
import { Product } from './models/product';
@Injectable({
providedIn: 'root'
})
export class ProductService {
constructor(private db: AngularFireDatabase) { }
create(product) {
return this.db.list('/products').push(product);
}
getAll(){
return this.db.list('/products').snapshotChanges()
.pipe(
map(actions =>
actions.map(a => ({ key: a.key, ...a.payload.val() }))
)
);
}
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();
}
}
products.component.ts
import { ActivatedRoute } from '@angular/router';
import { CategoryService } from './../category.service';
import { ProductService } from './../product.service';
import { Component, OnInit } from '@angular/core';
import { Product } from '../models/product';
import { Observable } from 'rxjs';
@Component({
selector: 'app-products',
templateUrl: './products.component.html',
styleUrls: ['./products.component.css']
})
export class ProductsComponent {
products: Product[];
categories$: Observable<any[]>;
category: string;
filteredProducts: Product[];
constructor(
productService: ProductService,
categoryService: CategoryService,
route : ActivatedRoute) {
productService.getAll().subscribe(a => this.products = a); //error on this.products:
//"Type 'unknown[]' is not assignable to type 'Product[]'."
// "Type '{}' is missing the following properties from type 'Product': title, price, category, imageUrl"
this.categories$ = categoryService.getAll();
route.queryParamMap.subscribe(params => {
this.category = params.get('category');
this.filteredProducts = (this.category) ?
this.products.filter(p => p.category === this.category) : this.products;
});
}
}
【问题讨论】:
标签: angular typescript