Angular 4 如何在解析器中返回多个可观察对象 [英] Angular 4 How to return multiple observables in resolver

查看:23
本文介绍了Angular 4 如何在解析器中返回多个可观察对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所述,我需要返回多个可观察对象或结果.目标基本上是加载一个图书馆列表,然后根据该图书馆 ID 加载书籍.我不想在组件中调用服务,而是希望在页面加载之前加载所有数据.

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:我的服务通过Id加载了这个方法

PS: My service got this method to load by Id

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

推荐答案

我找到了这个问题的解决方案,也许会对某人有所帮助,所以基本上我已经使用 forkJoin 来组合多个 Observable 并解决所有这些.

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.

这篇关于Angular 4 如何在解析器中返回多个可观察对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆