Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
})
like image 445
hxdef Avatar asked Feb 06 '26 09:02

hxdef


1 Answers

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.

like image 184
hxdef Avatar answered Feb 09 '26 10:02

hxdef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!