角路由器重定向到第一个选项

时间:2018-12-21 20:40:50

标签: angular angular-routing

我一直在尝试使用第一个sectionId重定向到子路由(如果为空)。

例如:导航到 / docs 需要重定向 / docs / first-steps

const DOCUMENTATION_ROUTES: Routes = [
  {
    path: '',
    component: DocumentationPage,
    resolve: { data: DocumentationResolver },
    children: [{ path: ':id', component: DocumentationDetailComponent }]
  }
]; 

DocumentationResolver 具有页面(各节)所需的所有数据。

    @Injectable()
    export class DocumentationResolver implements Resolve<Documentation[]> {
      constructor(
        private documentationService: DocumentationService,
        private glossaryService: GlossaryService,
        private router: Router
      ) {}

      resolve(route: ActivatedRouteSnapshot): Observable<any[]> {
        return forkJoin(
          this.documentationService.getDocumentation(),
          this.glossaryService.getGlossary()
        ).pipe(
          tap(([documentations]) => {

// this works but makes two calls

            const firstSectionTitle: string = documentations[0].titleNavigation;
            if (!route.firstChild) {
              this.router.navigate(['/docs', firstSectionTitle] });
            }
          })
        );
      }
    }

DocumentationPage :带有侧栏的包含部分的输入页面。 DocumantationDetailComponent :呈现所选部分的子组件。此外,它还会注入DocumentationResolver以获取数据。

1 个答案:

答案 0 :(得分:1)

您的路线配置:

const DOCUMENTATION_ROUTES: Routes = [
  {
    path: '',
    component: DocumentationPage,
    resolve: { data: DocumentationResolver },
    children: [{ path: ':id', component: DocumentationDetailComponent }]
  }
]; 

是说路由器的主插座应该包含DocumentPage组件,听起来像在工作吗?

有人说,只有提供ID才能显示孩子。

如果没有ID,您要显示的是默认路由?

如果是这样,那么您需要这样的东西:

children: [
  { path: ':id', component: DocumentationDetailComponent },
  { path: '', redirectTo: 'firstSteps', pathMatch: 'full' }
]

我不确定确切的语法,因为我不确定firstSteps在您的路由层次结构中的位置。但是类似的事情应该起作用。