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

Angular router redirect to first option

我一直在尝试重定向到第一个 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 以获取数据。

您的路线配置:

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

是说主路由器出口应该包含 DocumentPage 组件,这听起来像是在工作?

它说只有提供了 id 才显示 child。

你要的是没有id时显示的默认路由?

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

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

我不确定确切的语法,因为我不确定 firstSteps 在您的路由层次结构中的哪个位置。但类似的东西应该有用。