![](/img/trans.png)
[英]Promise.all Error: Uncaught (in promise) TypeError: #<Promise> is not iterable
[英]ERROR Error: Uncaught (in promise): TypeError: this.products is not iterable. (but it is iterable)
我想从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.
奇怪的是,
GetAllProducts()
进行console.log()
时,产品变量中的所有数据都很好getDistinctCategoryValues()
的console.log()
) 时,产品变量显示未定义IDK出了什么问题。 为什么数据在 1 行之后就消失了? [参见构造函数]。 我的 API 正在运行并且那里没有错误。
[顺便说一句,我正在为 JSON 使用https://www.npmjs.com/package/json-server ]
这是因为您的GetAllProducts
是异步 function,它等待响应const response = await this.dataService.GetProducts()
; which means any code scoped inside the GetAllProducts
function won't run, meanwhile anything running after the async function will run normal hence why your this.product will always return undefined to solve this move the getDistinctCategoryValues()
inside the await function or make GetAllProducts
return products 然后在getDistinctCategoryValues()
中使用它,或者使用生成器函数
您只需要更改产品:任何; 到产品 = []; 其他所有想法都应该在没有任何改变的情况下工作。
和
构造函数(私有数据服务:数据服务,私有路由器:路由器){ this.GetAllProducts(); this.getDistinctCategoryValues(); }
不管用。 你需要移动 this.getDistinctCategoryValues(); 到 ngOnInit,或调用 this.GetAllProducts()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.