在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<any> {
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所以必须有一个更好的方式。
答案 0 :(得分:28)
好吧,我希望我没有误解这个问题。
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'];
}
}
在完成/完成所有结算之前,路线不会被激活。
答案 1 :(得分:0)
使用“仅一个解析器”可以达到相同的结果:
resolve(route: ActivatedRouteSnapshot,state: RouterStateSnapshot,): Observable<any> {
let companyIdentifierTypes = this.companiesService.getCompanyIdentifierTypes();
let mobilePrefixes = this.registrationService.getMobilePrefixes();
let data = {companyIdentifierTypes: companyIdentifierTypes, mobilePrefixes: mobilePrefixes};
return Observable.of(data);
}
并以这种方式获取解析的数据:
fetchDataBeforeViewRender() {
let data = this.route.snapshot.data['data'];
if(data != null) {
data.companyIdentifierTypes.subscribe(data => {this.identityTypeIDList = data;});
data.mobilePrefixes.subscribe(data => {this.mobilePrefixOptions = data;});
}
}
确保正确命名解析器!