我试图列出数据从我的API调用与代码下面,我遇到了两个问题...
我的API调用:
getProducts(id: number) {
return from(Preferences.get({ key: 'TOKEN_KEY' })).pipe(
switchMap(token => {
const headers = new HttpHeaders().set('Authorization', `Bearer ${token.value}`);
return this.httpClient.get(`${environment.apiUrl}products?category=${id}`, { headers, observe: 'response' });
}),
catchError(err => {
console.log(err.status);
if (err.status === 400) {
console.log(err.error.message);
}
if (err.status === 401) {
this.authService.logout();
this.router.navigateByUrl('/login', { replaceUrl: true });
}
return EMPTY;
}),
map(res => res.body)
);
}
我的代码:
export class SubcategoryPage implements OnInit {
subcategory: any = [];
products: any = [];
constructor(
private route: ActivatedRoute,
private categoriesService: CategoriesService,
) { }
ngOnInit() {
this.getSubCategory();
this.getProducts();
}
getSubCategory() {
const id = Number(this.route.snapshot.paramMap.get('id'));
console.log('Izbrana podkategorija:', id);
this.categoriesService.getSubCategory(id).subscribe(
data => {
this.subcategory = data;
console.log('Podatki izbrane podkategorije:', data);
},
error => {
console.log('Error', error);
});
}
getProducts() {
const id = Number(this.route.snapshot.paramMap.get('id'));
const productsData = this.products.products;
this.categoriesService.getProducts(id).subscribe(
data => {
this.products = data;
console.log('Seznam izdelkov:', data);
this.products = productsData.map(products => {
products.qty = 0;
return products;
});
},
error => {
console.log('Error', error);
});
}
incrementQty(index: number) {
this.products[index].qty += 1;
}
decrementQty(index: number) {
this.products[index].qty -= 1;
}
}
此代码在浏览器控制台中返回以下内容,但不显示任何内容:
如果我添加下面的代码:
// I added this below products: any = [];
productsData = this.products.data;
// This I added inside getProducts() function bellow the console.log()
this.products = this.productsData.map(products => {
products.qty = 0;
return products;
});
我在浏览器控制台中收到此错误:
Cannot read properties of undefined (reading 'map')
下面是我的API返回的内容:
{
"products": [
{
"id": 2,
"status": 1,
"vat": "9.50",
"sort_order": 1,
"seo_url": "test",
"short_description": "short descripiton",
"image": null,
"name": "test",
"price": "235.0000",
"product_code": "45623146546",
"unit": "kos",
"min_weight": "1.00",
"step": "1.00",
"regime": null
},
{
"id": 3,
"status": 1,
"vat": "9.50",
"sort_order": 1,
"seo_url": "test",
"short_description": "short descripiton",
"image": "a3iwnk5uwjkr89fxu0atrbvdosiqcjmzegnl46yh1dlqge7zcp-1669899135.jpg",
"name": "test",
"price": "235.0000",
"product_code": "45623146546",
"unit": "kos",
"min_weight": "1.00",
"step": "1.00",
"regime": null
}
],
"tags": [
{
"tags": "test"
}
]
}
我做错了什么,我错过了什么吗?
1条答案
按热度按时间mi7gmzs61#
API调用没有返回任何内容,您应该首先检查这一点!
代码返回undefined,因为您需要做一个小的更改。