angular2延迟加载路由forchild导航relativeTo

时间:2017-06-17 16:38:37

标签: angular routing loading lazy-evaluation

我懒得加载模块,我定义了自己的路线。

我错过了模块的“根”路径(代码中的模块根路径) router.navigate(PATH,{relativeTo:this._activatedRoute})。

我错过了什么?

代码(为了清楚起见,省略了import和co):

// app-routing.module.ts
const appRoutes: Routes = [
  { path: 'module-root-path',
    loadChildren: './child/child.module#ChildModule',
  },
  ...,
];

@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes)
  ],
  exports: [ RouterModule, ]
})
export class AppRoutingModule { }




//ChildModule
const moduleRoutes: Routes = [
  { path: '',
    component: moduleComponent1,
    canActivateChild: [ ModuleGuard, ],
    children: [
      { path: '',
        component: moduleComponent2,
      },
    ]
  },
];

@NgModule({
  declarations: [
  ],
  imports: [
    RouterModule.forChild(moduleRoutes),
  ],
  exports: [ RouterModule ]
})
export class ChildRoutingModule {}

// ***** The code of the guard ****
// ModuleGuard
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { CanActivate, CanActivateChild, CanLoad,
         ActivatedRouteSnapshot, RouterStateSnapshot,
         Route, Router, ActivatedRoute } from '@angular/router';

@Injectable()
export class ModuleGuard implements CanActivateChild {
  constructor(
    private _router: Router,
    private _activatedRoute: ActivatedRoute
  ) {}

  canActivateChild(
    route: ActivatedRouteSnapshot,
    routerState: RouterStateSnapshot
  ): boolean {
    if (SOMETHING_NOT_TRUE) { return true; }

    // This does not work as I'm getting path
    //    /path_relative and not /module-root-path/path_relative
    this._router.navigate(
      ['path_relative'],
      { relativeTo: this._activatedRoute,
        queryParams: { returnUrl: routerState.url }
      }
    );

    return false;
  }
}

0 个答案:

没有答案