加载第一个子路由后,Angular2路由无法正常工作

时间:2016-12-15 00:12:24

标签: angular angular2-routing

我的路线配置方式如下:

RouterModule.forRoot([
    { path: '', redirectTo: 'main', pathMatch: 'full' },
    { path: 'main', component: SummaryComponent, children: [
        { path: 'data/:deviceId/:incidentId', component: DeviceMetricsComponent },
        { path: 'incident/analysis/:incidentId', component: IncidentAnalysisComponent },
      ] 
    },
    { path: 'test', component: TestFullPageComponent, children: [
        { path: 'test2', component: TestFullPageChildComponent}
      ] 
    },

    { path: 'logs/jobs/:jobtype', component: JobLogsComponent, pathMatch: 'full' },
    { path: '**', redirectTo: 'main' }
])

这是我的“主要”模板:

<div class="row">
    <div class="col-md-12">
        <!-- Some links are in this table that load into the router-outlet below -->
        <app-incident-node-table [tableTitle]="incidentNodeTableTitle" [parentSubject]="incidentNodesSubject"></app-incident-node-table>
    </div>
</div>
<div class="row" style="margin-top: 500px;">
    <div class="col-md-12">
        <div id="childResult">
            <router-outlet></router-outlet>
        </div>
    </div>
</div>

首次导航到该页面并点击链接时,会按预期加载到<router-outlet>。那时我的网址就像http://localhost:4200/main/incident/analysis/3816913766390440113

该表中悬停的任何其他链接都会显示不同的网址,但是,点击后,新内容不会加载到<router-outlet>

修改 IncidentNodeTable模板中的链接如下所示:

<span><a pageScroll [pageScrollOffset]="60" [routerLink]="['/main/incident/analysis', row.IncidentId]">Analyze</a></span>

1 个答案:

答案 0 :(得分:6)

未加载新内容的原因是您使用的是ActivatedRoute "params",这是一个Observable,因此路由器可能无法在导航到同一组件时重新创建该组件。在您的情况下,参数正在更改,而不重新创建组件。 所以尝试这种解决方案

    export class IncidentAnalysisComponent implements OnInit, OnDestroy {
      id: number;
      limit: number;
      private sub: any;

      constructor(private route: ActivatedRoute) {}

      ngOnInit() {
        this.sub = this.route.params.subscribe(params => {
           this.id = +params['id']; 
           this.limit = 5; // reinitialize your variable 
           this.callPrint();// call your function which contain you component main functionality 
        });
      }
     ngOnDestroy() {
        this.sub.unsubscribe();
    }
}

我希望这对你有用:)

相关问题