0

I have to make 2 http request. The first http request for return a list of url and some strings. Then I need to make another http request on this url to get anther data and append this data with the strings I got from the first http request.

How should I do this in angularJs2

Right now I can make the first http request using observable but I am stuck in getting the second http request.

I have been looking at observables,flatmap and mergemap, but I am new to both angular2 and observables and it is kind of confusion.

So my questions is what is the best way to chain this two request?

1 Answer 1

1

This answer is not specific to Angular, but mostly shows how to chain Reactive operators together to get what you need. You can do something like the following (warning: untested code):

import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switch';

export class Foo {
    bar() {
        const httpClient: HttpClient = /* Your HTTP client here */;
        httpClient
            .get<UrlAndString[]>('first url')
            .map(urlsAndStrings => {
                const parameter = doSomethingWithUrlsAndStrings(urlsAndStrings);
                return httpClient
                    .get<SecondResult>(`second url?param=${parameter}`)
                    .map(secondResult => { return [urlsAndStrings, secondResult]; });
            })
            .switch()
            .subscribe(tuple => {
                console.log(tuple[0]); // The urls and strings, of type UrlAndString[].
                console.log(tuple[1]); // The second result, of type SecondResult.
            });
    }
}

The import statements bring in the map and switch operators so that you can chain them.

map transforms events as they come through, so you can see that when the first .get() returns something it will be mapped to another Observable<T>. So the type signature of the first map function will be map<UrlAndString[], Observable<[UrlAndString[], SecondResult]>>. Meaning it will return an Observable<Observable<[UrlAndString[], SecondResult]>>, or an Observable that publishes Observables which publish tuples of type UrlAndString[] and SecondResult.

switch takes an Observable<Observable<T>> and turns it into an Observable<T>. The documentation I linked to above explains it better than I can. But you can see that the return type of that .switch() will be an Observable<[UrlAndString[], SecondResult]>.

The .subscribe() you're probably already familiar with.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.