简体   繁体   中英

Angular2 Routing not working after first child route is loaded

My routes are configured the following way:

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' }
])

Here is my "main" template:

<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>

When I first navigate to the page and click a link, it loads into the <router-outlet> as expected. At that point my url becomes something like http://localhost:4200/main/incident/analysis/3816913766390440113 .

Any additional links hovered in that table do display a different URL, however, once they are clicked, the new content isn't loaded into the <router-outlet> .

EDIT: The links in the IncidentNodeTable template look like this:

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

The reason new content isn't loaded is you are using ActivatedRoute "params" which is an Observable so router may not recreate the component when you navigating to the same component. In your case the parameter are changing without the component being recreated. So try this kind of solution

    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();
    }
}

i hope this will work for you :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM