Home > Enterprise >  Angular .map() returning empty array or showing error
Angular .map() returning empty array or showing error

Time:12-10

I'm trying to list out data from my API call with the code bellow and I am running into two issues...

My API call:

getProducts(id: number) {
    return from(Preferences.get({ key: 'TOKEN_KEY' })).pipe(
      switchMap(token => {
        const headers = new HttpHeaders().set('Authorization', `Bearer ${token.value}`);
        return this.httpClient.get(`${environment.apiUrl}products?category=${id}`, { headers, observe: 'response' });
      }),
      catchError(err => {
        console.log(err.status);
        if (err.status === 400) {
          console.log(err.error.message);
        }
        if (err.status === 401) {
          this.authService.logout();
          this.router.navigateByUrl('/login', { replaceUrl: true });
        }
        return EMPTY;
      }),
      map(res => res.body)
    );
  }

My code:

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('Izbrana podkategorija:', id);

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

  getProducts() {
    const id = Number(this.route.snapshot.paramMap.get('id'));
    const productsData = this.products.products;
    this.categoriesService.getProducts(id).subscribe(
      data => {
        this.products = data;
        console.log('Seznam izdelkov:', data);
        this.products = productsData.map(products => {
          products.qty = 0;
          return products;
        });
      },
      error => {
        console.log('Error', error);
      });
  }

  incrementQty(index: number) {
    this.products[index].qty  = 1;
  }

  decrementQty(index: number) {
    this.products[index].qty -= 1;
  }

}

This code return this in browser console and display nothing: enter image description here

if I add the code bellow:

// 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;
      });

I get this error in the browser console:

Cannot read properties of undefined (reading 'map')

Here is what my API returns:

{
    "products": [
        {
            "id": 2,
            "status": 1,
            "vat": "9.50",
            "sort_order": 1,
            "seo_url": "test",
            "short_description": "short descripiton",
            "image": null,
            "name": "test",
            "price": "235.0000",
            "product_code": "45623146546",
            "unit": "kos",
            "min_weight": "1.00",
            "step": "1.00",
            "regime": null
        },
        {
            "id": 3,
            "status": 1,
            "vat": "9.50",
            "sort_order": 1,
            "seo_url": "test",
            "short_description": "short descripiton",
            "image": "a3iwnk5uwjkr89fxu0atrbvdosiqcjmzegnl46yh1dlqge7zcp-1669899135.jpg",
            "name": "test",
            "price": "235.0000",
            "product_code": "45623146546",
            "unit": "kos",
            "min_weight": "1.00",
            "step": "1.00",
            "regime": null
        }
    ],
    "tags": [
        {
            "tags": "test"
        }
    ]
}

What am I doing wrong? have I missed something?

CodePudding user response:

The API call returns nothing, you should first check that!

The code is returning undefined, because you need to make a small change.

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('Izbrana podkategorija:', id);

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

  getProducts() {
    const id = Number(this.route.snapshot.paramMap.get('id'));
    this.categoriesService.getProducts(id).subscribe(
      (data: any) => { { // <- latest change here
        console.log('Seznam izdelkov:', data);
        const productsData = data.products;
        this.products = productsData.map(products => {
          products.qty = 0;
          return products;
        });
      },
      error => {
        console.log('Error', error);
      });
  }

  incrementQty(index: number) {
    this.products[index].qty  = 1;
  }

  decrementQty(index: number) {
    this.products[index].qty -= 1;
  }

}
  • Related