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

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

问题描述

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

Basically as a title states, I need to return multiple observables or maybe a results. The goal is basically to load lets say a library list and then load a books based on that library ID's. 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 books 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) => {
...

推荐答案

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

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天全站免登陆