Retrieve the status callback function from the service

Can anybody show me how to set up a call-back function between a component and a service? I apologize for my lack of experience with Angular and TypeScript.

getDiscount(){
    let getDisc = [];
    getDisc.push({
      price: Number(this.commonService.getPayments$.getValue())
    });
    
    this.commonService._getGlobalDiskaun(getDisc[0])
    setTimeout(() => this.getResult(),1000); 
  }

I've been attempting to implement the code above, but I keep getting null results when the network is slow. How can I write a code that waits for

this.commonService._getGlobalDiskaun(getDisc[0])
to return a value before calling this.getResult()?

Answer №1

The reason for this issue is that the setTimeout function you are using has a 1-second delay, which may not be enough time for the API response to arrive. To resolve this, you should subscribe to the service you are utilizing so that you can execute the function immediately upon receiving the API response, like so:

this.commonService._getGlobalDiscount(getDisc[0]).subscribe(result => this.getResult())

Additionally, make sure to return data in your service as shown below:

_getGlobalDiscount(){
   return this.http.get<any>(`${your_api_address}`)
}

It doesn't matter if it's a POST request; the important thing is that you return the response in your service.

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

Trouble with embedding video in the background using Next.js and Tailwind CSS

This is the code snippet for app/page.tsx: export default function Home() { return ( <> <main className='min-h-screen'> <video muted loop autoPlay className="fixed -top ...

Error in Typescript: "Cannot assign to parameter that is of type 'never'"

Here is the code snippet that I am working with: FilesToBlock: []; //defined in this class //within a method of the class this.FilesToBlock = []; this.FilesToBlock.push({file: blockedFile, id: fileID}); However, I'm encountering an issue with fil ...

Rendering illuminated component with continuous asynchronous updates

My task involves displaying a list of items using lit components. Each item in the list consists of a known name and an asynchronously fetched value. Situation Overview: A generic component named simple-list is required to render any pairs of name and va ...

Tips for fixing the issue of 'expect(onClick).toHaveBeenCalled();' error

Having trouble testing the click on 2 subcomponents within my React component. Does anyone have a solution? <Container> <Checkbox data-testid='Checkbox' checked={checked} disabled={disabled} onClick={handl ...

Can a mapped union type be created in TypeScript?

Can the features of "mapped types" and "union types" be combined to generate an expression that accepts the specified interface as input: interface AwaActionTypes { CLICKLEFT: 'CL'; CLICKRIGHT: 'CR'; SCROLL: 'S'; ZOOM ...

Encountering error code TS1003 while trying to access object properties using bracket notation in Typescript

How can object property be referenced using bracket notation in TypeScript? In traditional JavaScript, it can be done like this: getValue(object, key) { return object[key]; } By calling getValue({someKey: 1}, "someKey"), the function will return 1. H ...

What could be causing the TypeScript type error within this Effector effect subscriber?

Working on a front-end application utilizing React, Typescript, Effector, FetchAPI, and other technologies. Created an Effector effect to delete an item in the backend: export const deleteItemFX = createEffect({ handler: (id: string) => { return ...

Select one of 2 parameters and begin typing

I recently encountered a situation where I needed to define a type with an id field (string) and an oldId field (number), but I wanted these fields to be exclusive. For example: { id: "1234", name: "foo" } { oldId: 1234, name: "b ...

Creating formGroups dynamically for each object in an array and then updating the values with the object data

What I am aiming to accomplish: My goal is to dynamically generate a new formGroup for each recipe received from the backend (stored in this.selectedRecipe.ingredients) and then update the value of each formControl within the newly created formGroup with t ...

I am integrating and connecting my angular2 library with my primary project by placing it in the node_modules folder within the library's build directory. This process is expected to

I have developed an Angular2 component as a library and I am connecting this library to my main project. After building my library, a build folder is created. However, when I run npm-link inside the build folder, it generates a node_modules folder with al ...

Backdrop styling for Material-UI dialogs/modals

Is there a way to customize the semi-transparent overlay of a material-ui dialog or modal? I am currently using material-ui with React and Typescript. https://i.stack.imgur.com/ODQvN.png Instead of a dark transparent overlay, I would like it to be transp ...

Vue 3 - Compelled to utilize any data type with computedRef

Recently, I've been diving into Vue/Typescript and encountered a puzzling error. The issue revolves around a class named UploadableFile: export class UploadableFile { file: File; dimensions: Ref; price: ComputedRef<number>; ... constr ...

Tips for infuriating TSC with Lookup categories

I'm looking for the Typescript compiler (TSC) to throw errors when I make mistakes in signatures. export class EventEmitter<EventTypes extends { [key: string]: any }> { subscribe<Event extends keyof EventTypes>(type: keyof EventTypes, ...

Achieve validation of numerous variables without the need for a string of if-else

If we have three variables, such as firstName, lastName, and email, how can we check if they are empty or not without using multiple if else blocks? let firstName = "John"; let lastName = "Doe"; let email = "john.doe@example.com"; if (firstName.trim() == ...

Hey there world! I seem to be stuck at the Loading screen while trying to use Angular

A discrepancy in the browsers log indicates node_modules/angular2/platform/browser.d.ts(78,90): error TS2314: Generic type 'Promise' is missing 2 type arguments. ...

Help with Material-UI: Passing unique props to a custom TreeItem component

I am trying to pass an argument category to the component CustomTreeItem which uses TreeItemContent. Documentation: https://mui.com/ru/api/tree-item/ import TreeItem, { TreeItemProps, useTreeItem, TreeItemContentProps, } from '@material-ui/lab ...

Error encountered when trying to update tree structure in TypeScript with new data due to incorrect array length validation

I have encountered an issue with my tree data structure in TypeScript. After running the updateInputArray(chatTree); function, I am getting an “invalid array length” error at the line totalArray.push(iteratorNode.data);. Furthermore, the browser freeze ...

What causes the variable to be undefined in the method but not in the constructor in Typescript?

I am currently working on an application using AngularJS 1.4.9 with Typescript. In one of my controllers, I have injected the testManagementService service. The issue I'm facing is that while the testManagementService variable is defined as an object ...

Preventing JavaScript Compilation for a Specific Folder using tsconfig: A Step-by-Step Guide

To create my own npx package, I'm currently working on converting my .ts files into .js. The purpose of the application is to generate TypeScript templates for users based on their selected options. In this app, there's a CLI called 'index.t ...

Issue: Attempting to assign a 'boolean' variable to a type of 'Observable<boolean>' is not compatible

I am currently working on the following code: import {Injectable} from '@angular/core'; import {ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree} from '@angular/router'; import {Observable} from 'rxjs' ...