1

I have a route in Angular where I pass an id to load an element from my database. In my component I load the element using the following code:

this.route.params
        .map((params: Params) => params['id'])
        .switchMap((id: number) => this.service.getElement(id))
        .catch((e) => {
            return Observable.throw(e);
        })
        .subscribe((data: Models.IElement) => {
            this.element= data as Models.IElement;
            this.setTitle();
        }, () => this.router.navigate(['/']));

Where this.service.getElement(id) makes an http call and returns an Observable. It all goes well. The problem I have now is that I want to issue a second http call and I don't know where to add the code for the second service http call (it would be a similar method to getElement, receiving an id as parameter).

More info: The second http call would ideally be issued in parallel to the getElement call. It only depends on the id from the Params.

How can I make this work using Observables? Is there any way to make it work?

3
  • Where do you want to make that second call ? On what is it based ? On previous response ? the route params id ? Give more info please Commented Feb 28, 2017 at 16:40
  • It's only based on the id. Ideally it would be issued in parallel to the getElement call. Commented Feb 28, 2017 at 16:41
  • 2
    I don't have time to give you a solution right now, but take a look into Fork Join, it's the equivalent of Promise.all. It'll subscribe to every Observables you pass, and then will wait for every one of them to finish before continuing. Of course, they're launched in parallel. I let you try something and later if don't succeed I'll help :) Commented Feb 28, 2017 at 16:56

1 Answer 1

1

Using @Maxime's comment I came with the following code:

this.route.params
        .map((params: Params) => params['id'])
        .switchMap((id: number) => {
            this.id = id;
            return Observable.forkJoin([this.service.getElem(id), this.service.getElemDocs(id)]);
        })
        .catch((e) => {
            return Observable.throw(e);
        })
        .subscribe(([elem, documents]) => {
            this.elem= elemas Models.IElement;
            this.elemDocuments = documents;
            this.setTitle();
        }, () => this.router.navigate(['/']));

This launches both calls at the same time and waits for completition from both.

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.