Angular 2:同级子路由共享同一个解析器

Angular 2: Sibling child routes sharing same resolver

我想弄清楚是否有更优化的方法来在两个同级子路由之间共享同一个解析器。下面是路由如何与解析器相关的示例。

import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { NgModule } from '@angular/core';
export const routes = [{
        path: '',
        component: parentComponent,
        canActivate: [AuthGuard],
        resolve: {
            someData: someDataResolver
        },
        children: [
            { path: '', redirectTo: '0', pathMatch: 'full' },
            { path: '0', 
                component: someComponent1,
                resolve: {
                    someData1: someData1Resolver,
                    someData2: someData2Resolver,
                }
            },
            { path: '2', 
                component: someComponent2,
                resolve: {
                    someData2: someData2Resolver
                }
            }
            ... a bunch more children routes/components with resolvers

        ]
    }]

现在,我正在为每个子路由重复解析器调用,我认为这不是最佳选择。有谁知道是否有更好的方法来共享来自共享同级子解析器的数据?我考虑过将重复解析器中的数据设置为共享服务,然后另一个子同级路由将从该服务访问数据(而不是在解析器中进行另一个 api 调用)。还有其他更优的方案吗?

您可以使用无组件父路由添加额外的级别并将解析器上移到此级别:

import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { NgModule } from '@angular/core';
export const routes = [{
        path: '',
        component: parentComponent,
        canActivate: [AuthGuard],
        resolve: {
            someData: someDataResolver
        },
        children: [
            { path: '', 
                resolve: {
                    someData2: someData2Resolver
                },

            children: [
                { path: '', redirectTo: '0', pathMatch: 'full' },
                { path: '0', 
                    component: someComponent1,
                    resolve: {
                        someData1: someData1Resolver,
                    }
                },
                { path: '2', 
                    component: someComponent2,
                }
                ... a bunch more children routes/components with resolvers
            ]
        ]
    }]