【发布时间】:2020-10-18 11:25:18
【问题描述】:
我想从 JSON 数组中获取唯一值。
数据来自 fetch 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()时,products 变量中的所有数据都正常 - 但是当我从
getDistinctCategoryValues()console.log()时,产品变量显示未定义
IDK 出了什么问题。为什么数据在 1 行之后就消失了? [参见构造函数]。我的 API 正在运行,没有错误。
[顺便说一句,我将https://www.npmjs.com/package/json-server 用于 JSON ]
【问题讨论】:
标签: javascript json angular typescript json-server