Multiple asynchronous calls in Angular 2

In my Component, there is a function that is supposed to return a value (Promise). This value requires information from two distinct sources: an API call and data from a database.

The method in question looks like this:

public getValue(): Promise<number> {

    return this.dataProvider.loadData().toPromise().then(data => {
        return data.feePerc
    }).then(feePerc => {
        let url = `${apiUrl}/mycontroller/value`            
        return new Promise<number>(resolve => {                
            return this.http.get(url)
                .map(response => {                       
                    let value = response.json()
                    return resolve(value * (1 + (feePerc / 100)))
                })
        })
    })
}

However, the function does not work as intended. While the feePerc value is returned successfully, using http.get within a Promise seems to be causing issues. The map() function is never executed.

I initially thought about handling these asynchronous functions simultaneously and synchronizing their results before returning the final outcome. Despite struggling with an elegant solution using promises, I have yet to figure out a proper chained approach.

package.json:

  • "@angular/core": "4.2.5",
  • "rxjs": "5.4.2",

Answer №1

map() is not being utilized as you never subscribe to the observable.

Your use of promises in this scenario is considered an antipattern, and it's worth noting that there shouldn't be a need for promises when working with observables, as they offer built-in mechanisms for chaining operations.

(By the way, it's rather unusual to apply toPromise() in the initial call, which is the correct method to convert an observable to a promise, but then not use it in the subsequent call.)

The following code snippet demonstrates the proper approach:

public getValue(): Observable<number> {
    const url = `${apiUrl}/mycontroller/value`;

    return this.dataProvider.loadData()
      .map(data => data.feePerc)
      .switchMap(feePerc => 
        this.http.get(url).map(response => response.json() * (1 + (feePerc / 100))));
}

Please take into account that Angular 2 has been around for nearly two years now, with the current version being 6.x. It's advisable to consider upgrading, particularly transitioning to RxJS 6 and HttpClient among other enhancements.

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

Angular 7 TypeScript code not updating value

UPDATE: I'm having trouble with my code not updating the selected value with the new one entered in the input field "newVb". The error message says 'this.newVarde' is undefined when it reaches the line 'this.selectedVarde = this.newVard ...

What is the best way to evaluate typing into an input field?

My objective is to test the 'typing' functionality in an input element. The aim is to insert a value into the input element, verify that its binding successfully captures the value, and observe the entered value within the input element. Below i ...

What is the best way to invoke a method in a child component from its parent, before the child component has been rendered?

Within my application, I have a parent component and a child component responsible for adding and updating tiles using a pop-up component. The "Add" button is located in the parent component, while the update functionality is in the child component. When ...

The situation I find myself in frequently is that the Angular component Input

There seems to be an issue with a specific part of my application where the inputs are not binding correctly. The component in question is: @Component({ selector : 'default-actions', templateUrl : './default.actions.template.html&a ...

Enhancing DOM Elements in a React Application Using TypeScript and Styled-Components with Click Event

I've been working on an app using React, Typescript, and styled components (still a beginner with typescript and styled components). I'm trying to create a simple click event that toggles between which of the two child components is visible insid ...

Tips for removing a row from a DataGrid column with the click of a button

I am facing a challenge with my data table that contains users. I am trying to implement a delete button for each row, but it seems like the traditional React approach may not work in this situation. Currently, I am utilizing the DataGrid component in the ...

When Typescript calls the toString method on a Function, it produces unexpected characters like "path_1, (0, promises.writeFile)"

I'm currently attempting to convert a function into a string for transmission to a worker thread for execution. However, when imported code is included, the resulting string contains strange characters. import { HttpStatus } from '@nestjs/common& ...

Struggling to identify the error while utilizing Jasmine's throwError function

I am relatively new to using Jasmine and have been experimenting with the toThrowError() function. However, I can't seem to get my test to pass successfully. In one of my functions, I purposely throw an error: test.service.ts test(list:{}){ if ...

Observables waiting inside one another

I've encountered an issue where I need to return an observable and at times, within that observable, I require a value from another observable. To simplify my problem, let's consider the following code snippet: public dummyStream(): Observabl ...

Encountering issues while attempting to run an npm install command on the package.json file

Having trouble running npm install to set up my Angular project on a Mac. It seems like the issues are due to working with an older project. npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @angular-devkit/< ...

Using ternary operator to set multiple variables in setState

Conditional Operator for Setting State in React I am wondering if there is a way to set the state with a variable that holds the correct state value using setState method. interface state { isfiltered: array<boolean> } this.setState({ ...

The onChange event for React input does not trigger when the value remains the same

Script: function SingleInput(props: {value: string; onChanged: (value: string) => void}) { const handleChange = useCallback( (e: React.ChangeEvent<HTMLInputElement>) => { const newValue = e.target.value; cons ...

Issue when transferring properties of a component to a component constructed Using LoadingButton MUI

Check out my new component created with the LoadingButton MUI: view image description here I'm having issues passing props to my component: view image description here Dealing with a TypeScript problem here: view image description here I can resolv ...

I am unable to locate the type definition file for 'core-js' at the moment

Currently, I am in the process of developing an application using angular2 along with angular-cli. Surprisingly, angular-in-memory-web-api was not included by default. In order to rectify this, I took the initiative to search for it and manually added the ...

Tips on Configuring the Attributes of a TypeScript Object in Angular 2

A TypeScript class called Atom is defined as follows: export class Atom { public text: String; public image: boolean; public equation: boolean; } To create an object of type Atom class and set its properties, the following steps are used: atom: ...

Retrieving information from the Dog API using axios and storing the results in a fresh array

Currently, I am working on a NextJS app using Typescript. My issue lies in the functionality aspect of the application. I am utilizing the Dog API to retrieve all the breeds names and store them in a new array of arrays. Each sub-array contains the breed a ...

What is the best way to implement ES2023 functionalities in TypeScript?

I'm facing an issue while trying to utilize the ES2023 toReversed() method in TypeScript within my Next.js project. When building, I encounter the following error: Type error: Property 'toReversed' does not exist on type 'Job[]'. ...

In Angular, when a component is clicked, it is selecting entire arrays instead of just a single item at a

I am currently working on implementing a rating feature using Angular. This component will be used to rate different languages based on how proficient I am with them. My issue lies in the fact that when I click on one array element, it automatically selec ...

Tips for fixing type declaration in a generic interface

Here is a simple function that constructs a tree structure. interface CommonItem { id: string parent: string | null } interface CommonTreeItem { children: CommonTreeItem[] } export const generateTree = <Item extends CommonItem, TreeItem extends ...

Is it no longer possible to instantiate an object using the syntax <interface>{}?

There seems to be an issue with the code snippet below when run in the TypeScript playground: interface Person { name: string; age: number; } const makePerson= function(name : string, age : number) : Person { let obj = <Person>{} ...