Alex 75
Alex 75

Reputation: 3246

Two (or more) asynchronous call in Angular2

I have a function in a Component that should returns a valu (Promise). To obtain that value I need the information from 2 different sources. Let the sources be an API call and a database data.

The method is 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)))
                })
        })
    })
}

It does not work. The feePerc value is returned but probably It is wrong to return http.get because it is Observable and also if I wrapped it in a Promise it does not work.

Actually the map() function is never raised up.

My initial idea was to call these two asynchronous functions and use a sort of semaphore to return the final result when I have both the sources but I'm still struggling with the simple chained solution.

package.json:

Upvotes: 0

Views: 840

Answers (1)

JB Nizet
JB Nizet

Reputation: 691913

map() is never called because you never subscribe to the observable.

You're using promises antipatterns here, and you shouldn't need promises anyway, since observables natively have ways to chain observables.

(BTW, it's quite strange to use toPromise() in the first call, which is the correct way to transform an observable to a promise, but not to use it in the second one).

All you need is

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

Note that Angular 2 is now almost 2 years old. Thec current version is 6.x. It's time to upgrade, and, among other things, to switch to RxJS 6 and HttpClient.

Upvotes: 2

Related Questions