0

我有这个路由表:

// Routing array - set routes to each html page
const appRoutes: Routes = [
  { path: '', redirectTo: '/courses', pathMatch: 'full' },
  { path: 'courses', component: CourseListComponent,  pathMatch: 'full'},
  { path: 'courses/:id', component: CourseDetailComponent, pathMatch: 'full' },
  { path: 'courses/:id/unit/:unitId', component: CoursePlayComponent,
    children: [
      { path: '', component: CourseListComponent },
      { path: 'lesson/:lessonId', component: CourseLessonComponent, data: 'lesson },
      { path: 'quiz/:quizId', component: CourseQuizComponent, data: 'quiz, }
  ]},
  { path: '**', component: PageNotFoundComponent, pathMatch: 'full' }];

//Course-Play.component
     
     constructor(private courseService: CourseService,
          private route: ActivatedRoute,
          private router: Router,
          public sanitizer: DomSanitizer) {
            route.url.subscribe(() => {
                console.log(route.snapshot.children.data); }); // <-- undefined
          }
          
     ngOnInit() {
     
     // this is what I want to do but I don't know how
     if (this.route.snapshot.children.data == 'lesson) {
        // activate lesson children
      }
      else {
        // activate quiz children
       }
     
     }

在课程播放中的 ngOnInit 中,我想知道路线是课程/:课程 ID 还是测验/:测验 ID。我只需要知道路线中是否有课程或测验,然后激活不同的孩子。我知道如何使用参数(使用 route.snapshot)但不使用静态文本。

编辑:试图使用数据,但它不工作

4

1 回答 1

1

这是一种可能的方法(在您的组件中ngOnInit),this.route作为一个注入到您的构造函数中ActivatedRoute

import { ActivatedRoute, UrlSegment } from '@angular/router';

constructor(private route: ActivatedRoute) {}

ngOnInit() {
  this.route.url.subscribe((urlSegments: UrlSegment[]) => {
    switch (urlSegments[4].path) {
      case 'lesson':
        // ...
        break;
      case 'quiz':
        // ...
    }
  });
}

编辑:刚刚意识到您正在使用子组件,我不确定在这种情况下这些段的行为方式。试试看,如果这不起作用,我会删除这个答案。

于 2018-10-07T08:39:11.297 回答