过滤数组代码不会呈现假定的过滤项目 Angular 9



我有这个 JSON:

[
{
"products": [
{
"id": "1",
"name": "Apple",
"price": "free",
"category": "Fruits"
},
{
And so on

而这个:

[{
"categories": [
{
"name": "Fruits"
},
{
"name": "vegetables"
},
{
"name": "Meat"
}
]
}]

服务数据、类别和产品:

export class DataService {
constructor(@Inject(String) private url: string, private http: HttpClient) { }

public getAll(): Observable<any> {
return this.http.get(this.url)
}
}
export class ProductService extends DataService {
constructor(http: HttpClient) { 
super('assets/products.json', http)
}
}
export class CategoriesService extends DataService {
constructor(http: HttpClient) { 
super('assets/categories.json', http)
}
}

来自 home 组件的调用:

export class HomeComponent implements OnInit {
categories: Categories[];
products: Products[]=[];
filteredProducts: Products[]=[];
category:string;;
constructor(
private categoriesService: CategoryService,
private productService: ProductService,
private route: ActivatedRoute) {
this.categoriesService.getAll().subscribe(categories => {
this.categories = categories[0]['categories']
})
this.productService.getAll().subscribe(p => {
this.products = p[0]['products']
console.log(this.products)
})
this.route.paramMap.subscribe(params=>{
this.category = params.get('category');
this.filteredProducts=(this.categories)? 
this.products.filter(p=> p.category.toLowerCase()===this.category.toLowerCase()) :
this.products
});
}

和渲染主页 HTML:

<div class="container">
<div class="row">
<div class="col-md-4">
<mat-list role="list" *ngFor="let c of categories">
<a role="listitem" routerLink='/home' [queryParams]='{categories: c.name}'>
{{c.name}}
</a>
</mat-list>
</div>
<div class="col-md-8">
<ul>
<li *ngFor="let f of filteredProducts">
{{f.name}}
</li>
</ul>
</div>
</div>
</div>

所以问题是我可以呈现类别,当我选择它们时,URL 会发生变化。目前为止,一切都好。但是过滤器过程的实现不起作用。我没有收到任何错误,但我也没有显示。有人可以帮我弄清楚我错过了什么吗?(控制台.log这个文件转换器 Rpoducts 给了我一个数组,所以我在组件中获取数据(

您的类别订阅比您的路线订阅晚触发,从而伪造您的类别? 路由订阅中的条件。您需要确保在从服务收到类别数据后筛选数据。

export class HomeComponent implements OnInit {
categories: Categories[];
products: Products[]=[];
filteredProducts: Products[]=[];
category:string;;
constructor(
private categoriesService: CategoryService,
private productService: ProductService,
private route: ActivatedRoute) {}
ngOnInit() {
this.route.paramMap.subscribe(params=>{
this.category = params.get('category');
forkJoin([this.getCategories(), this.getProducts()]).subscribe(() =>  {
this.filteredProducts=(this.categories)? 
this.products.filter(p=> p.category.toLowerCase()===this.category.toLowerCase()) :
this.products; 
});
})
}
public getCategories(): Observable<boolean> {
return this.categoriesService.getAll().pipe(map(categories => {
this.categories = categories[0]['categories']
return true;
}));
}
public getProducts(): Observable<boolean> {
return this.productService.getAll().pipe(map(p => {
this.products = p[0]['products']
console.log(this.products)
return true;
}));
}

最新更新