"Dealing with Angular .map() function returning an empty array or displaying error messages

I'm encountering two issues while attempting to display data from my API call using the following code...

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

Your Code:

export class SubcategoryPage implements OnInit {
  subcategory: any = [];
  products: any = [];

  constructor(
    private route: ActivatedRoute,
    private categoriesService: CategoriesService,
  ) { }

  ngOnInit() {
    this.getSubCategory();
    this.getProducts();
  }

  // More methods and functions...

Browser Console Error:

Cannot read properties of undefined (reading 'map')

Sample API Response:

{
    // Sample API response for reference
}

What could be causing the error in your code?

Answer №1

Ensure the API call is returning data before proceeding.

If you are getting undefined from the code, consider making a minor adjustment.

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('Data of selected subcategory:', 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('List of products:', 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;
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

how to use an object as a key in the groupBy function with underscore.js

My JSON structure is as follows: I am attempting to group by NodeGroup using the underscore library. vm.populatedNodeGroups = _($scope.nodes).groupBy(function (o) { return o.NodeGroup.Name; }); Within vm.populatedNodeGroups, ...

Evaluate easy Ajax- Success Function

Today, I am experimenting with testing a basic Ajax request using Jasmine: var Card = { single : function(params){ $.ajax({ dataType: "json", headers: {"X-TOKEN": TOKEN}, url: SERVER, success: fu ...

Ways to modify the text color of a dropdown button upon clicking by leveraging ViewChild and ElementRef techniques

I'm attempting to change the color of text in my dropdown menu button after it's clicked using @Viewchild and elementRef. However, the method I've tried doesn't seem to be working as expected. <div class="dropdown"> ...

Steps for designing a movable image

I'm looking to implement a feature where the user can drag and drop an image anywhere on the page. Once the user places the image, its position will be saved so that when they revisit the page, it will be in the same location. Thank you! ...

Executing Javascript code from a specified web address

Let's say I have an image that needs to be shifted vertically, and I achieve it using the following code snippet: document.getElementById('ImgID1').style.verticalAlign = However, the value by which I need to shift the image is provided thr ...

How can I populate an array to use in a datatable when rendering?

How can I ensure that my datatable renders with the proper data on my webpage without needing to interact with the sort button? Where should I populate the array for use in a datatable so that it occurs before the rendering? export function MyComponent() ...

Managing user sessions in Node.js

What is the best way to manage SESSIONS in Node.js? Specifically, I am interested in storing a UserID in a session using Node.js. How can this be accomplished, and is it possible to access that Node.js session in PHP as well? I am looking for an equivale ...

Enhance the functionality of Javascript Promise.then by allowing the argument function to accept an extra parameter

In my code, I am currently utilizing ES6 Promise as shown below: const ctx = {} Promise.resolve() .then(() => doSomethingWith(ctx)) .then((retValue) => doSomethingElseWith(retValue, ctx)) I wish to achieve something like this: const ctx = {} u ...

Is it possible to modify the year in the bsDatepicker to a different value?

Currently in my TypeScript code, I am importing the { BsDatepickerModule } from 'ngx-bootstrap/datepicker'; Here is the HTML code snippet I have: <div class="col-xs-12 col-12 col-md-4 form-group"> <input type="text" placehold ...

Saving an array to a database in Concrete5

I have created a block where multiple names can be dynamically added. However, when I click save and return to edit the block, the newly added names are not visible. I suspect there is an issue with saving to the database. Can someone please assist me with ...

My simple application is experiencing a problem where ComponentDidMount is not being invoked

I used a tool called create-react-app to build this simple application. Strangely, the ComponentDidMount method is never getting invoked. import React, { Component } from "react"; class App extends Component { componentDidMount() { console.log("M ...

Tally the values entered into the text input field

I am interested in counting the number of IDs within an input of type "text" The values return like this: 1, 4, 6, etc. <input type="hidden" class="selected_ids" value="selected_ids" name="selected_ids[]" multiple="yes" id="selected_ids" /> ...

Testing NodeJS Database Functionality using Mocha and Asserting with should.js

Currently, I am in the process of testing my NodeJS application using mocha and should. The issue I am facing is that while the first test executes smoothly, the second one fails with an error of null. Interestingly, both tests result in a valid user being ...

Adjustable div height: reduce until reaching a certain point and then begin expanding once more

Incorporating a hero section to display content is my current approach. The design adapts responsively utilizing the padding-bottom percentage strategy, along with an inner container that is absolutely positioned for central alignment of the content. The ...

Guide on conducting unit tests for the provided code in Angular 8

I am currently working on implementing unit testing for this specific code snippet. applyFilter(filterValue: string) { this.dataSource.filter = filterValue.trim().toLowerCase(); this.DMDataSource.filter = filterValue.trim().toLowerCase(); // con ...

Troubleshooting VueJS, Electron, and Webpack integration with Hot Reload feature

I have been immersed in a new project that involves utilizing Electron, VueJS, and Webpack for HMR functionality. Unfortunately, I am encountering difficulties with the Hot Module Replacement feature not working as expected. Here is my current configurati ...

Access my account on the one.com control panel using the identical login credentials

I am curious if it's possible to implement a login page on my website for customers and then seamlessly redirect them to the control panel on one.com without requiring them to re-enter their username and password? Visit the action page on one.com her ...

Implementing TypeScript for augmented styling properties in a component - a guide

I have custom components defined as follows: import React from 'react'; import styled from '../../styled-components'; const StyledInput = styled.input` display: block; padding: 5px 10px; width: 50%; border: none; b ...

Having trouble submitting the edit form

I had the idea to create an edit form that would replace the existing data in a table for editing. However, I am facing issues with getting the form to submit properly even though the create form is functioning correctly. Below is the code snippet that I n ...

It appears that the Cypress test is not taking into account the mat-paginator pageSize

Currently, I am troubleshooting a bug within an integration test that is supposed to verify the functionality of switching between pages using mat-paginator. The paginator has a pageSize set to 20, and the response fixture contains 24 'items'. My ...