Search code examples
angularangular-routingangular-httpangular-httpclient

Angular 4 How to return multiple observables in resolver


As the title states, I need to return multiple observables or maybe results. The goal is basically to load let's say a library list and then load books based on that library IDs. I don't want to call a service in components, instead I want all the data to be loaded before the page load.

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { UserService } from './../_services/index';

@Injectable()
export class LibraryResolver implements Resolve<any> {
    constructor(private _userService: UserService) {}

    resolve(route: ActivatedRouteSnapshot) {
        return this._userService.getLibraryList();
    }
}

How can I load library list first and then load book info for each library and return to my component?

PS: My service got this method to load by Id

this.userService.getLibraryBooks(this.library["id"]).subscribe((response) => {
 // response processing
})

Solution

  • I found a solution for this issue, maybe will help somebody, so basically I've used forkJoin to combine multiple Observables and resolve all of them.

    resolve(route: ActivatedRouteSnapshot): Observable<any> {
            return forkJoin([
                    this._elementsService.getElementTypes(),
                    this._elementsService.getDepartments()
                    .catch(error => {
    
                        /* if(error.status === 404) {
                            this.router.navigate(['subscription-create']);
                        } */
    
                        return Observable.throw(error);
                    })
            ]).map(result => {
                return {
                    types: result[0],
                    departments: result[1]
                };
            });
        };
    

    Now it works correctly, as intended.