填寫這份《一分鐘調查》,幫我們(開發組)做得更好!去填寫Home

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...

方法

      
      resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<T> | Promise<T> | T
    
引數
route ActivatedRouteSnapshot
state RouterStateSnapshot
返回值

Observable<T> | Promise<T> | T

使用說明

如果同時指定了守衛和解析器,則直到所有守衛都執行併成功後,解析器才會執行。例如,考慮以下路由配置:

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.