Angular 2+路由组件中的代码未运行

时间:2018-02-20 00:05:20

标签: angular angular-routing

我在路线上有一个Angular组件(它内部有一个路由器插座)。模板中的任何内容都按预期显示,并且路由器插座按预期工作,因此我知道路由设置正确;但是,组件的TypeScript似乎没有运行。如果我使用routerLink导航或从路线启动应用程序并不重要。构造函数或ngOnInit似乎都没有运行。我正在使用Angular 5.2.5。

@Component({
  template: `This is visible. <router-outlet></router-outlet>`
})
export class ApplicationComponent implements OnInit {

  constructor(sectionPagingService: SectionPagingService) {
    this.test();
  }

  ngOnInit() {
    this.test();
  }

  test() {
    alert('hello');
    console.log('hello');
  }

}

export const applicantRoutes: Routes = [
  {
    path: 'application',
    children:
      [
        { path: '', component: ApplicationComponent },
        { path: ':id',  children: [
          { path: 'media', component: MediaEditComponent },
          { path: 'birth', component: BirthEditComponent },
          { path: 'social', component: SocialEditComponent },
          { path: 'citizenship', component: CitizenshipEditComponent },
          { path: 'insurance', component: InsuranceEditComponent },
          { path: 'education', component: EducationEditComponent },
          { path: 'military', component: MilitaryEditComponent },
          { path: 'bankruptcy', component: BankruptcyEditComponent },
          { path: 'divorce', component: DivorceEditComponent },
          { path: 'certifications', component: CertificationsEditComponent },
        ] }
      ]
  },
  {
    path: 'instructions',
    component: InstructionsComponent
  },
  {
    path: 'confirmation',
    component: ConfirmationComponent
  }
];

我在这里缺少什么。

1 个答案:

答案 0 :(得分:1)

事实证明我没有path: 'application'的组件集。或者你可以说我ApplicationComponent在错误的地方。应该是:

export const applicantRoutes: Routes = [
  {
    path: 'application',
    component: ApplicationComponent,
    children:
      [
        { path: '', component: ApplicationShimComponent },
        { path: ':id',  children: [
          { path: 'media', component: MediaEditComponent },
          { path: 'birth', component: BirthEditComponent },
          { path: 'social', component: SocialEditComponent },
          { path: 'citizenship', component: CitizenshipEditComponent },
          { path: 'insurance', component: InsuranceEditComponent },
          { path: 'education', component: EducationEditComponent },
          { path: 'military', component: MilitaryEditComponent },
          { path: 'bankruptcy', component: BankruptcyEditComponent },
          { path: 'divorce', component: DivorceEditComponent },
          { path: 'certifications', component: CertificationsEditComponent },
        ] }
      ]
  },
  {
    path: 'instructions',
    component: InstructionsComponent
  },
  {
    path: 'confirmation',
    component: ConfirmationComponent
  }
];