我是较新的角度显影器,我具有以下要求的角度cli规格 -Angular CLI:7.0.7节点:10.13.0 OS:win32 x64 Angular:7.0.4 但是有1个错误发生。错误是
src / app / products / products.component.ts(28,12)中的ERROR:错误TS2322: 类型“ {}”不可分配给类型“产品[]”。属性“长度” 类型“ {}”中缺少。
product.component.ts
import { Product } from 'src/app/models/product';
import { ActivatedRoute } from '@angular/router';
import { CategoryService } from './../category.service';
import { ProductService } from './../product.service';
import { Component } from '@angular/core';
import 'rxjs/add/operator/switchMap';
@Component({
selector: 'app-products',
templateUrl: './products.component.html',
styleUrls: ['./products.component.css']
})
export class ProductsComponent {
products: Product[] = [];
filteredProducts: Product[] = [];
categories$;
category: string;
constructor(
route: ActivatedRoute,
productService: ProductService,
categoryService: CategoryService
) {
productService
.getAll()
.switchMap(products => {
this.products = products;
return route.queryParamMap;
})
.subscribe(params => {
this.category = params.get('category');
this.filteredProducts = (this.category) ?
this.products.filter(p => p.category === this.category) :
this.products;
});
this.categories$ = categoryService.getAll();
}
}
以下行.switchMap(products => { this.products =产品; //此行发生错误 返回route.queryParamMap;
答案 0 :(得分:1)
正确的方法是像这样在您的服务中添加键入内容
class ProductService {
getAll() {
this.http.get<Product[]>(...);
}
}
这会将您的响应类型转换为Observable<Product[]>
,错误将消失
答案 1 :(得分:0)
您可能想要更改
.switchMap(products => {
...
}
到
.switchMap((products: Product[]) => {
...
}