【问题标题】:Angular .map() returning empty array or showing errorAngular .map() 返回空数组或显示错误
【发布时间】:2022-12-09 20:06:39
【问题描述】:

我正在尝试使用下面的代码列出我的 API 调用中的数据,我遇到了两个问题......

我的代码:

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('Selected subcategory:', id);

    this.categoriesService.getSubCategory(id).subscribe(
      data => {
        this.subcategory = data;
        console.log('Selected subcategory data:', data);
      },
      error => {
        console.log('Error', error);
      });
  }

  getProducts() {
    const id = Number(this.route.snapshot.paramMap.get('id'));

    this.categoriesService.getProducts(id).subscribe(
      data => {
        this.products = data;
        console.log('Products list:', data);
      },
      error => {
        console.log('Error', error);
      });
  }

}

此代码在浏览器控制台中返回此内容并且不显示任何内容:

如果我添加以下代码:

// 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')

我究竟做错了什么?我错过了什么吗?

【问题讨论】:

    标签: javascript angular typescript ionic-framework


    【解决方案1】:

    API 调用不返回任何内容,您应该先检查一下!

    代码返回未定义,因为您需要做一点小改动。

    // I added this below  products: any = [];  
    const productsData = this.products.products; // <- changed here
    
    // This I added inside getProducts() function bellow the console.log()
          this.products = productsData.map(products => { // <- changed here
               products.qty = 0;
               return products;
          });
    

    【讨论】:

      猜你喜欢
      • 2014-09-11
      • 1970-01-01
      • 2015-11-25
      • 1970-01-01
      • 2023-01-20
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      • 2016-01-13
      相关资源
      最近更新 更多