ToDo
ToDo

Reputation: 782

Angular 2 - Route with multiple parameters not loading its assigned component twice

I have a child route that accepts :id and :type. They work individually and load the component assigned to them, but the component only loads once when they are used together id/:type and not again when the :id or :type is updated.

Examples:
myapp/1 -> This loads (for :id)
myapp/b -> This loads (for :type)
myapp/1/b -> This loads but only once (for combination of :id/:type)
myapp/2/b -> This doesn't load the component again (when :id is updated)

I can see the URL changing correctly in the browser for all the routes.

Code of child route class:

export const CHILD_ROUTES: Routes = [
    { path: '', component: TitleComponent },
    { path: ':id', component: TitleComponent },
    { path: ':id/:type', component: TitleComponent } //This componment doesn't load
];


The code used to change/manipulate the routes:
this.router.navigate(['/myapp', this.id]);
this.router.navigate(['/myapp', this.id, this.type]);

Please let me know if anything else is required.

Upvotes: 1

Views: 857

Answers (1)

Amit kumar
Amit kumar

Reputation: 6147

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 here
           this.callPrint();// call your function which contain you component main functionality 
        });
      }
     ngOnDestroy() {
        this.sub.unsubscribe();
    }
}

i hope this will help :)

Upvotes: 1

Related Questions