Issue with Angular Ionic HTTP promise functionality not performing as expected

My service retrieves data from an endpoint :

Service.ts

  getAllProducts(){
    return new Promise( (resolve, reject) => {
      this.apiService.get( this.allProducts, `/products`, {} )
        .then( data => resolve( data.map( item => this.parseProductDetails( item ) ) ) )
        .catch( err => reject( err ) );
    } );
  }

console.log(data) - shows all products. The service is working fine and the function this.parseProductDetails also returns products correctly.

However, when I call it from the component :

ionViwDidLoad(){
  this.productProvider.getAllProducts()
          .then( () => {
            items => this.items = items; 
            console.log('All products', this.items)
          }  )
          .catch( err => console.debug( 'products not found', err ) )
}

console.log('All products', this.items)
- nothing is returned in the console log, not even undefined or the 'All products' text.

What is wrong with this code and what do I need to change in order to retrieve the information in the component?

parseProductDetails(item) :

protected parseProductDetails( data: any ): Object {
    let parsed: any = data;

    try {
      parsed.dimensions = JSON.parse( data.dimensions );
    } catch( e ) { parsed.dimensions = []; }

    if( data.price )
      parsed.priceFormatted = this.formatPrice( data.price, data.currency );
    else
      parsed.priceFormatted = false;

    if( data.delivery )
      parsed.deliveryFormatted = this.formatPrice( data.delivery, data.currency );
    else
      parsed.deliveryFormatted = false;

    if( data.stock )
      parsed.stockFormatted = this.formatStock( data.stock, data.stockUnit );
    else
      parsed.stockFormatted = false;

    return parsed;
  }

returning parsed as an array.

Answer №1

Examining the challenges with promises and callbacks:

When working with promises and callbacks, it is important to handle potential errors effectively. Here is an example code snippet showcasing how products are retrieved:

Answer №2

There seems to be an issue with your code where you are using two arrow functions inside the then() method. It would be best to remove one of them to avoid any potential conflicts.

ionViewDidLoad(){
  this.productProvider.getAllProducts()
          .then( (items) => {
            this.items = items; 
            console.log('All products', this.items)
          })
          .catch( err => console.debug( 'products not found', err ) )
          .then( () => loading.dismiss() );
}

Answer №3

It appears that there are multiple issues at play here. While the exact cause is unclear, it seems that the items parameter may not be placed correctly. Consider revising the code snippet below:

fetchProducts() {
  return this.apiService.get(this.allProducts, `/products`, {}).then((data) => { 
    console.log('items', data);
    return data.map((item) => this.parseProductDetails(item))
  });
}

This function can be invoked as follows:

ionViewDidLoad(){
  this.productProvider.fetchProducts()
    .then((items) => {
      this.items = items;
      console.log('All products', this.items)
    })
    .catch((err) => console.debug( 'Error fetching products', err ))
    .then(() => loading.dismiss());
}

Answer №4

It is recommended to utilize async and await in your code.

async fetchAllItems()
await this.itemService.fetchAllItems()

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

`transpilePackages` in Next.js causing Webpack issue when used with Styled Components

I'm encountering an issue while utilizing components from a custom UI library in a repository. Both the repository and the web app share the same stack (React, Typescript, Styled Components) with Next.js being used for the web app. Upon running npm ru ...

Installation of Angular-cli is successful but system still shows error of Angular-cli not being installed

https://i.sstatic.net/dINO9.png These are the packages included in my project: "license": "MIT", "dependencies": { "@angular/animations": "^4.0.3", "@angular/common": "^4.0.3", "@angular/compiler": "~4.0.0", "@angular/core": "~4.0.0", ...

Tips for confirming a sub string is present in an array using JavaScript/TScript

I am currently testing for the presence of a SubString within an array. In my test, I am asserting using: expect(classList).toContain('Rail__focused') However, I encountered the following error: Error: expect(received).toContain(expected // inde ...

Prevent toggle button from activating panel expansion

Is there a way to add toggle buttons to the description section of an expansion panel without triggering the expansion panel when interacting with the buttons? I have included an example here. ...

When using the map function, I am receiving an empty item instead of the intended item based on a condition

Need assistance with my Reducer in ngRx. I am trying to create a single item from an item matching an if condition, but only getting an empty item. Can someone please help me out? This is the code for the Reducer: on(rawSignalsActions.changeRangeSchema, ...

I am looking to refund the sum

I need assistance with returning an amount from a specific function. I have created a function called getWalletTotalAmont() getWalletTotalAmont() { let amount = 0; this.http.post<any>(`${this.generalService.apiBaseUrl}api/wallet/getWalletTotal ...

Issues encountered when retrieving data with ReactiveForms

My current project involves gathering data using ReactiveForms. Here is the structure of my setup: Initially, I create a modal to gather the necessary data: async present(){ const modal = await this.modalController.create({ component: dataComponent, cs ...

Resolving Node.js Troubles: An Encounter with 'Module Not Found' Error

After generating a new application, I encountered an error while using the "ionic serve" command. [ng] The specified path cannot be found. [ng] internal/modules/cjs/loader.js:883 [ng] throw err; [ng] ^ [ng] Error: 'C:\Users\shane\Co ...

Can we create an alias for the import path in TypeScript?

import A = require('../../distant/PathToA'); import B = require('./different/path/PathToB'); I am utilizing external modules (commonJS) and browserify, with WebStorm as my editor. If this were just regular javascript, there are severa ...

retrieve information from Angular service

Is there a way for parent components to communicate with child components by injecting providers directly into the TypeScript file of each child component? I am trying to retrieve data using get and set methods, but I am unsure how to proceed. Any suggesti ...

The properties of the Angular data service are not defined

I've encountered an issue while working with Angular services. Specifically, I am using one service to make requests with an SDK and another service to manage wallet data. Strangely, when trying to use the wallet-service within the SDK-service, it app ...

concerning the integration of CSRF token in the GuestPayment feature

Greetings and thank you for taking the time to help me out. I am currently working on a project in AngularJS 2.0 where users need to be able to pay their pending bills through a GuestPayment portal. This portal does not require any login credentials and ...

What is the best way to create a straightforward interface using TypeScript?

Although I'm sure this question has been asked before, I couldn't find the answer on Google or SO. So here it goes: I am looking to create an interface with a key named id of type number. Additionally, there may be other keys with unknown names ...

Automatically selecting the country phone code based on the country dropdown selection

When the country dropdown is changed, I want the corresponding phone code dropdown to be dynamically loaded. <div class="row"> <div class="col-sm-8 col-md-7 col-lg-6 col-xl-5 pr-0"> <div class="form-group py-2"> <l ...

What is the best way to compare an array with comma-separated values in JavaScript?

I have a scenario where I have two arrays, one for categories and the other for products. Each product contains multiple categories as a comma-separated string. My goal is to match a specific category with each product's product_category value and the ...

How to apply CSS classes to dynamically injected HTML in Angular 7

One of the challenges I'm currently facing is how to assign a CSS class based on a calculation in my component. Here's a snippet from my component class: @Component({ selector: 'app-render-json', template: `<div [innerHtml ...

What is the reason for TS expressing dissatisfaction about the use of a type instead of a type entry being provided

Below is a snippet of code for a Vue3 component that takes in an Array of Objects as a prop: <script lang="ts"> interface CorveesI { What: string, Who: string, Debit: number } export default { name: 'Corvees', props: { ...

Angular 2 - ERROR: The value of 'ngClassUntouched' expression has been modified after the initial check

The error message is as follows: angular2.dev.js:23597 EXCEPTION: Expression 'ngClassUntouched in myComponent@7:12' has been modified after it was checked. Previous value: 'true'. Current value: 'false' in [ngClassUntouched ...

What is the process for embedding images in Angular that are stored in a directory other than assets?

I am working on an Angular Application with a particular structure outlined below: Structure Within the structure, there is a directory labeled backend (highlighted in yellow) containing other directories. An example of a valid path within this structure ...

The in-memory-web-api is failing to respond to queries when using Chrome

I've been experiencing an issue with my in-memory database setup. Even though I have registered everything correctly, I am not receiving any data back. There are no errors or 404 responses; it seems like the app is intercepting the request and returni ...