【发布时间】:2022-10-04 20:23:17
【问题描述】:
我在后端和前端都有带有类别名称的枚举:
export enum CategoryEnum {
All = 'All',
Category1 = 'Category1',
Category2 = 'Category2',
Category3 = 'Category3',
Category4 = 'Category4'
}
我以这种方式显示它们(shop.component.html - 这是经过多次试验):
<h5 class="text-warning ml-3">Categories</h5>
<ul class="list-group my-3">
<li class="list-group-item"
*ngFor="let category of categories | keyvalue"
[class.active]="category.value === this.categorySelected"
[value]="category.value"
(click)="onCategorySelected(category.value)">
{{category.value}}
</li>
</ul>
这是我的 shop.service.ts:
@Injectable({
providedIn: 'root'
})
export class ShopService {
baseUrl = 'https://localhost:5001/api/';
constructor(private http: HttpClient) { }
getProducts(category?: string) {
let params = new HttpParams();
if (category) {
params.append('category==', category);
//params.append('?Filters=category%3D%3D', category);
}
return this.http.get<IProduct[]>(this.baseUrl + 'products', {observe: 'response', params})
.pipe(
map(response => {
return response.body
})
);
}
}
在 Swagger 中,此查询显示正确的结果 (“%3D”等于“=”所以“category%3D%3D4”等于“category==4”): 卷曲 curl -X GET "https://localhost:5001/api/Products?Filters=category%3D%3D4" -H "accept: /" 请求网址 https://localhost:5001/api/Products?Filters=category%3D%3D4
经过多次尝试,单击前端显示相应产品的某个类别后,我无法解决该问题。 shop.componet.ts:
@Component({
selector: 'app-shop',
templateUrl: './shop.component.html',
styleUrls: ['./shop.component.scss']
})
export class ShopComponent implements OnInit {
products: IProduct[];
categories = Object.keys(CategoryEnum);
categorySelected: string;
constructor(private shopService: ShopService) { }
ngOnInit(): void {
this.getProducts();
}
getProducts() {
this.shopService.getProducts(this.categorySelected).subscribe((response: any) => {
this.products = response.data.$values;
}, error => {
console.log(error);
});
}
onCategorySelected(categoryName: string) {
this.categorySelected = categoryName;
this.getProducts();
}
}
如果可能的话,请提供简短的解释。
【问题讨论】:
-
您的代码中有错字。
params.append('category==', category)应该是params.append('category=', category) -
@E.Maggini 不幸的是没有帮助我。
-
错误是什么?
-
@E.Maggini 没有错误,只是在单击其中一个类别后无法检索/过滤相应的产品。
标签: html angular typescript enums