RC 4 中的 Angular 2 引入了 Route 的 resolve 属性。
此属性是具有实现 Resolve 接口的属性的对象。
每个解析器必须是@Injectable 并且具有返回 Observable|Promise|any 的方法 resolve。
当您将 ActivatedRoute 作为route 注入组件时,您可以从 route.snapshod.data['someResolveKey'] 访问每个已解析的属性。
来自 angular.io 文档的示例:
class Backend {
fetchTeam(id: string) {
return 'someTeam';
}
}
@Injectable()
class TeamResolver implements Resolve<Team> {
constructor(private backend: Backend) {}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<any>|Promise<any>|any {
return this.backend.fetchTeam(route.params.id);
}
}
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'team/:id',
component: TeamCmp,
resolve: {
team: TeamResolver
}
}
])
],
providers: [TeamResolver]
})
class AppModule {}
或者您也可以提供具有相同签名的函数而不是类。
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'team/:id',
component: TeamCmp,
resolve: {
team: 'teamResolver'
}
}
])
],
providers: [
{
provide: 'teamResolver',
useValue: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => 'team'
}
]
})
class AppModule {}
你可以在组件中获取数据:
export class SomeComponent implements OnInit {
resource : string;
team : string;
constructor(private route: ActivatedRoute) {
}
ngOnInit() {
this.team = this.route.snapshot.data['team'];
// UPDATE: ngOnInit will be fired once,
// even If you use same component for different routes.
// If You want to rebind data when You change route
// You should not use snapshot but subscribe on
// this.route.data or this.route.params eg.:
this.route.params.subscribe((params: Params) => this.resource = params['resource']);
this.route.data.subscribe((data: any) => this.team = data['team']);
}
}
希望对你有帮助,
愉快的黑客攻击!