在ui-router中,很容易在路由配置中定义多个解析,所以我们可以这样说:
export const APP_STATES: Ng2StateDeclaration[] = [
{
name: 'dashboard',
url: '/dashboard',
component: DashboardComponent,
resolve: [
{
token: 'playbookDurations',
deps: [DashboardService],
resolveFn: (svc: DashboardService) => svc.getPlaybookDurations()
},
{
token: 'playbookSuccesses',
deps: [DashboardService],
resolveFn: (svc: DashboardService) => svc.getPlaybookSuccesses()
},
{
token: 'playbookRuns',
deps: [DashboardService],
resolveFn: (svc: DashboardService) => svc.getPlaybookRuns()
},
{
token: 'activityLog',
deps: [DashboardService],
resolveFn: (svc: DashboardService) => svc.getActivityLog()
}
]
}
}];
使用Angular2路由器时,需要为resolve参数实现解析器模式.所以像这样:
import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Injectable } from '@angular/core';
import { DashboardService } from '.';
@Injectable()
export class DashboardResolver implements Resolve {
constructor(private dashboardService: DashboardService) { }
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
return this.dashboardService.get();
}
}
然后在我的路线中我做了类似的事情:
import { DashboardComponent } from './dashboard.component';
import { DashboardResolver } from './dashboard.resolver';
export const routes = [
{
path: '',
children: [
{
path: '',
component: DashboardComponent,
resolve: {
data: DashboardResolver
}
}
]
}
];
问题是只有一个决心.如何实现多个解析参数,如ui-router实现呢?
我想你有两个选择; 为每个输入实现解析器或让解析返回一个嵌套了所有解析的对象.第一个似乎非常礼仪,第二个听起来相当hacky所以必须有一个更好的方式.
好吧,我希望我没有误解这个问题.
Angular的路由器支持每条路由尽可能多的解析器.
在路由声明中,resolve
属性是一个对象,它可以包含您想要的任意数量的键:
{
path: '',
component: DashboardComponent,
resolve: {
foo: Resolver1
bar: Resolver2,
// more resolves here...
}
}
然后从组件中检索已解析的数据:
@Component({ ... })
export class MyComponent {
constructor(private route: ActivatedRoute) { }
ngOnInit() {
const foo = this.route.snapshot.data['foo'];
const bar = this.route.snapshot.data['bar'];
}
}
在所有结算完成/完成之前,路线不会被激活.