错误 错误: 未捕获 (在承诺中): 类型错误: 此产品不可迭代.(但它是可迭代的)



我想从JSON数组中获取唯一值。

数据来自提取 API。这显然是可迭代的

[注意产品变量是 JSON 的样本,实际上,我正在通过调用 GetAllProducts(( 来填充数据]

products = 
[
{
"name": "APPLE 27 inch THUNDERBOLT DISPLAY",
"show_room": "A iCenter",
"stock": "1",
"type": "DISPLAYS",
"category": "APPLE",
"id": "101"
},
{
"name": "APPLE WIRELESS KEYBOARD",
"show_room": "B iCenter",
"stock": "2",
"type": "MOUSE",
"category": "MAC ACCESSORIES",
"id": "107"
}
]

当我尝试执行此功能时发生错误:getDistinctCategoryValues((

这是我的.ts文件

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-product-list',
templateUrl: './product-list.page.html',
styleUrls: ['./product-list.page.scss'],
})
export class ProductListPage implements OnInit {
constructor(private dataService: DataService,
private router: Router) {
this.GetAllProducts();
this.getDistinctCategoryValues();
}
products: any;

ngOnInit() {
}
async GetAllProducts() {
const response = await this.dataService.GetProducts();
const dataService = await response.json();
this.products = dataService;
console.log(this.products);
}
getDistinctCategoryValues() {
const lookup = {};
const result = [];
console.log(this.products);
for (const item of this.products) {
const currentVar = item.category;
if (!(currentVar in lookup)) {
lookup[currentVar] = 1;
result.push(currentVar);
}
}
console.log(result);
return result;
}

}

现在当我运行getDistinctCategoryValues((时,我收到错误:

ERROR Error: Uncaught (in promise): TypeError: this.products is not iterable.

奇怪的是,

  1. 当我从GetAllProducts()console.log()时,产品变量中的所有数据都很好
  2. 但是当我从getDistinctCategoryValues()console.log()时,产品变量显示未定义

IDK出了什么问题。为什么数据在 1 行后消失?[请参阅构造函数]。我的 API 正在运行,那里没有错误。

[顺便说一句,我正在使用 https://www.npmjs.com/package/json-server 的JSON]

这是因为您的GetAllProducts是一个异步函数,并且它等待响应const response = await this.dataService.GetProducts();这意味着GetAllProducts函数内的任何代码都不会运行,同时在异步函数之后运行的任何内容都将正常运行,因此为什么您的this.product将始终返回未定义 要解决此问题,请在 await 函数中移动getDistinctCategoryValues()或使GetAllProducts返回产品,然后在getDistinctCategoryValues()中使用它,或使用生成器函数

您只需要更改产品:任何; 到产品 = []; 其他所有想法都应该在没有任何变化的情况下起作用。

构造函数(私有数据服务: 数据服务, 专用路由器:路由器( { 这。获取全部产品((; this.getDistinctCategoryValues((; }

行不通。你需要移动这个.getDistinctCategoryValues((;到ngOnInit,或者叫这个。获取全部产品((

最新更新