Resolve

一个接口,某些类可以实现它以扮演一个数据提供者。

Interface that class can implement to be a data provider.

查看"说明"...

      
      interface Resolve<T> {
  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<T> | Promise<T> | T
}
    

说明

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 {}
      
      
  1. class Backend {
  2. fetchTeam(id: string) {
  3. return 'someTeam';
  4. }
  5. }
  6.  
  7. @Injectable()
  8. class TeamResolver implements Resolve<Team> {
  9. constructor(private backend: Backend) {}
  10.  
  11. resolve(
  12. route: ActivatedRouteSnapshot,
  13. state: RouterStateSnapshot
  14. ): Observable<any>|Promise<any>|any {
  15. return this.backend.fetchTeam(route.params.id);
  16. }
  17. }
  18.  
  19. @NgModule({
  20. imports: [
  21. RouterModule.forRoot([
  22. {
  23. path: 'team/:id',
  24. component: TeamCmp,
  25. resolve: {
  26. team: TeamResolver
  27. }
  28. }
  29. ])
  30. ],
  31. providers: [TeamResolver]
  32. })
  33. class AppModule {}

你还可以转而提供一个具有 resolve 签名的函数:

You can alternatively provide a function with the resolve signature:

@NgModule({ imports: [ RouterModule.forRoot([ { path: 'team/:id', component: TeamCmp, resolve: { team: 'teamResolver' } } ]) ], providers: [ { provide: 'teamResolver', useValue: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => 'team' } ] }) class AppModule {}
      
      
  1. @NgModule({
  2. imports: [
  3. RouterModule.forRoot([
  4. {
  5. path: 'team/:id',
  6. component: TeamCmp,
  7. resolve: {
  8. team: 'teamResolver'
  9. }
  10. }
  11. ])
  12. ],
  13. providers: [
  14. {
  15. provide: 'teamResolver',
  16. useValue: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => 'team'
  17. }
  18. ]
  19. })
  20. class AppModule {}

方法

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

Observable<T> | Promise<T> | T