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

Is there a way to change a typescript enum value into a string format?

I'm working with enums in TypeScript and I need to convert the enum value to a string for passing it to an API endpoint. Can someone please guide me on how to achieve this? Thanks. enum RecordStatus { CancelledClosed = 102830004, Completed = ...

Mastering checkbox selection in Angular reactive formsLearn how to effortlessly manage the checked status of

I am struggling with setting the checked status of a checkbox control within an Angular reactive form. My goal is to change the value based on the checked status, but it seems like the value is controlling the status instead. For instance, I want the for ...

Discovering the functionality of es6 object.assign and find methods within a typescript file

Currently, I am in the process of transitioning from Java Script to TypeScript for my project. However, I am facing limitations as I am unable to utilize object.assign() and find methods. ...

The provided argument, which is of type 'RefObject<HTMLDivElement>', cannot be assigned to the parameter of type 'IDivPosition'

Currently, I am implementing Typescript with React. To organize my code, I've created a separate file for my custom function called DivPosition.tsx. In this setup, I am utilizing useRef to pass the reference of the div element to my function. However ...

A guide on transforming JSON data to an array format where nested arrays are encapsulated within objects using curly braces instead of square brackets in TypeScript

Retrieve data from a REST API in the following format: { "ProductID":1, "Category":[ { "CategoryID":1, "SubCategory":[ { "SubCategoryID":1, } ] } ] } I need to t ...

What role does the empty object type {} play in typescript?

In the @types/React package of the DefinitelyTyped library, I came across this definition: interface FunctionComponent<P = {}> { (props: PropsWithChildren<P>, context?: any): ReactElement | null; propTypes?: WeakValidationMap&l ...

Using the HERE Maps JavaScript API to implement custom styles from a JSON file

TLDR: How can I change the map style using a .json file from HERE maps editor? After creating a "custom" style in the new HERE map style editor and exporting it as a single .json file, I encountered difficulties applying this styling due to lack of clear ...

Creating a robust web application using Laravel API, Sanctum, Angular, and SSO with SAML authentication. Learn how to construct a sophisticated Laravel 7/8 backend API integrated with an Angular 11 front-end and

I am looking to transition my authentication system from laravel api + angular with sanctum to SAML authentication. After some research, I've found that using a laravel plugin like laravel-saml2 or laravel-saml2 would be necessary. (Interestingly eno ...

The unit tests are not triggering the execution of setTimeout

Currently, I am developing a project in TypeScript and for unit-tests, I am utilizing QUnit and sinonjs. One of the functions within my code dynamically renders UI elements. I need to retrieve the width of these dynamic elements in order to perform additio ...

Show a component on click event in Angular 4

Looking for a solution to create an event on a button click that triggers another component? When clicked again, the component should be reduced with a part always remaining visible. While I am currently using [ngClass]='hidden' within the same c ...

Loading a large quantity of items into state in React Context using Typescript

I am currently working on a React context where I need to bulk load items into the state rather than loading one item at a time using a reducer. The issue lies in the Provider initialization section of the code, specifically in handling the api fetch call ...

The 'split' property is not found on the 'Int32Array' type

ERROR located in src/app/account/phone-login/phone-login.component.ts(288,53): error TS2339: Property 'split' is not a valid property for type 'string | Int32Array'. Property 'split' cannot be found on type 'Int32Array& ...

Encountering Error when Attempting to Load Webpack Dependencies for Browser

I'm currently in the process of manually scaffolding an Angular 6 app (not using the CLI). Everything was going smoothly until I encountered a webpack error: ERROR in window is not defined After researching online, it seems like I may be missing som ...

Using Ionic 3 pipe for filtering lists based on comparison of 2 arrays

Looking for assistance in creating a customized filter PIPE component that can filter and display job postings based on selected search array words. I have been able to return results using one search value, but now need help modifying it to handle multipl ...

When a module with routes is imported into another module with lazy-loading, the routing system becomes disrupted

Within our angular application running version 4.3.6, we have implemented lazy-loaded modules such as Fleet, Maintenance, and Car. Examining our primary app router structure: const routes: Routes = [ { path: '', redirectTo: 'fleet', ...

Deploying a Spring Boot and Angular application

Looking for guidance in creating executable files with specific commands to run projects using Eclipse STS for Spring Boot applications and VS Code for Angular. Open to exploring other solutions as well. Struggling with the process of creating an executa ...

Retrieve the property of a Typescript object using a template argument

I am looking to develop a Typescript Collection class that can locate items by field. Here is an example of what I have in mind: class Collection<T, K keyof T> { private _items: T[]; public isItemInCollection(item: T) { return _item ...

Using TypeScript to Import Modules without Default Exports (CommonJS)

Can a module that is defined without a default export be imported using import module from 'module'; and then compiled to commonjs? An answer on Stack Overflow suggests that it might be possible with the use of the --allowSyntheticDefaultImports ...

The Angular overlay panel remains open consistently

I recently developed an Angular component similar to p-overlaypanel, but I'm facing an issue where it remains open for every item I click. What I actually want is for only one overlay panel to be clicked and shown at a time - if I click on another ove ...

How to implement angular 2 ngIf with observables?

My service is simple - it fetches either a 200 or 401 status code from the api/authenticate URL. auth.service.ts @Injectable() export class AuthService { constructor(private http: Http) { } authenticateUser(): Observable<any> { ...