仅在父路线渲染后渲染子路线

时间:2017-11-15 12:48:44

标签: angular angular2-routing angular-routing

我有一个路由结构

  path: '',
    component: MainComponent,
    children: [
      {path: 'employees', component: EmployeesComponent, canActivate: [AuthGuard], children: [
        {path: '', component: EmployeeListComponent, pathMatch: 'full', canActivate: [AuthGuard]},
        {path: ':id', component: EmployeeMainComponent, pathMatch: 'full',  canActivate: [AuthGuard]}
      ]}
    ]
  }

在主要组件ngOnInit中我得到子模块列表

getSubmodules(id) {
    this.universityAsideService.getSubmodules(id)
      .subscribe((subModules) => {
        this.subModules = subModules;
      this.saveSubModules(subModules).subscribe((data) => this.goToModule(id));
        console.log('submodules in getSubmodules, UniversityAside Co');
        console.log(this.subModules);
      });
  }

  saveSubModules(subModules): Observable<any> {
    return Observable.create((obs) => {
      obs.next(localStorage.setItem('subModules', JSON.stringify({
        subModules: subModules
      })));
    });
  }

然后,Emloyees组件从localstorage获取子模块列表,然后呈现视图。访问localhost:4200/#/employees/时遇到问题然后,在MainComponent保存到localstorage之前,employees组件尝试从localstorage获取子模块。我怎么解决这个问题 ?感谢。

1 个答案:

答案 0 :(得分:0)

实现AuthGuard以防止在父组件之前呈现子组件。

修改路线,如:

  path: '',
    component: MainComponent,
    canActivate: [AuthGuard],
    children: [
      {path: 'employees', component: EmployeesComponent, canActivate: [AuthGuard], children: [
        {path: '', component: EmployeeListComponent, pathMatch: 'full', canActivate: [AuthGuard]},
        {path: ':id', component: EmployeeMainComponent, pathMatch: 'full',  canActivate: [AuthGuard]}
      ]}
    ]
  }