Search code examples
angulartypescriptrxjsangular2-http

Resolve multiple promises and send angular 2 http request


I need to fetch two things from my storage, which gives me two Promises. Next up, I need to use these two promises to compose an angular 2 HTTP request. But I cant figure out a way to correctly compose these steps. I always end up with an Observable<Observable<Response>>.

    let tokenPromise = this.getToken()
    let registrationTokenPromise = this.getRegistrationToken()

    Observable.zip(
        tokenPromise,
        registrationTokenPromise,
        (token, registrationToken) => {
            let headers = this.headers(token)
            return this.http.post(`${this.apiBase}/users/registration-token`,
                { registration_token: registrationToken },
                headers
            )
        })

How can I correctly solve this to receive an Observable<Response>?


Solution

  • You are getting an Observable<Observable<Response>> because Observable.zip returns an Observable and the http.post returns an Observable. In order to unwrap one of the observables, you will need to subscribe to the Observable.zip

    Observable.zip(
            tokenPromise,
            registrationTokenPromise,
            (token, registrationToken) => {
                let headers = this.headers(token)
                return this.http.post(`${this.apiBase}/users/registration-token`,
                    { registration_token: registrationToken },
                    headers
                )
            })
            .subscribe(response => {
               //do something with response
            })