Resolve
可以实现为数据提供者的类的接口。数据提供者类可与路由器一起使用,以在导航期间解析数据。接口定义了开始导航时调用 resolve()
路由器在最终激活路由之前等待数据解析。
Interface that classes can implement to be a data provider. A data provider class can be used with the router to resolve data during navigation. The interface defines a resolve()
method that is invoked when the navigation starts. The router waits for the data to be resolved before the route is finally activated.
interface Resolve<T> {
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<T> | Promise<T> | T
}
说明
一个接口,某些类可以实现它以扮演一个数据提供者。
The following example implements a resolve()
method that retrieves the data needed to activate the requested route.
@Injectable({ providedIn: 'root' })
export class HeroResolver implements Resolve<Hero> {
constructor(private service: HeroService) {}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<any>|Promise<any>|any {
return this.service.getHero(route.paramMap.get('id'));
}
}
Here, the defined resolve()
function is provided as part of the Route
object in the router configuration:
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'detail/:id',
component: HeroDetailComponent,
resolve: {
hero: HeroResolver
}
}
])
],
exports: [RouterModule]
})
export class AppRoutingModule {}
你还可以转而提供一个具有 resolve
签名的函数:
You can alternatively provide an in-line function with the resolve()
signature:
export const myHero: Hero = {
// ...
}
@NgModule({
imports: [
RouterModule.forRoot([
{
path: 'detail/:id',
component: HeroComponent,
resolve: {
hero: 'heroResolver'
}
}
])
],
providers: [
{
provide: 'heroResolver',
useValue: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => myHero
}
]
})
export class AppModule {}
Further information available in the Usage Notes...
方法
参数
返回值
|
使用说明
如果同时指定了守卫和解析器,则直到所有守卫都运行并成功后,解析器才会执行。例如,考虑以下路由配置:
When both guard and resolvers are specified, the resolvers are not executed until all guards have run and succeeded. For example, consider the following route configuration:
{
path: 'base'
canActivate: [BaseGuard],
resolve: {data: BaseDataResolver}
children: [
{
path: 'child',
guards: [ChildGuard],
component: ChildComponent,
resolve: {childData: ChildDataResolver}
}
]
}
执行顺序为:BaseGuard、ChildGuard、BaseDataResolver、ChildDataResolver。
The order of execution is: BaseGuard, ChildGuard, BaseDataResolver, ChildDataResolver.