Search code examples
angularangular2-routingangular2-http

Angular 2 router parameters issue multiple http calls


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?


Solution

  • 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.