簡體   English   中英

ERROR 錯誤:未捕獲(承諾):TypeError:this.products 不可迭代。 (但它是可迭代的)

[英]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.

奇怪的是,

  1. 當我從GetAllProducts()進行console.log()時,產品變量中的所有數據都很好
  2. 但是當我來自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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM