Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular router navigation changes url, but doesn't render component

I am working on an angular application with routing and path parameter. With a button click, a function is called to redirect the user to a new URL with the same path parameter. Although the URL in the browser changes, the corresponding component defined in app-routing.module.ts is not loaded. If I refresh the page again, the correct page is rendered.

The idea is that a student gets a unique URL with a hash token (e. g. /student/33192c29aa8e449e94f3a1c4eef43ca8), which shows him some guidelines. Afterwards with a click he should be forwarded to a registration page with the same token (e. g. /student/registration/33192c29aa8e449e94f3a1c4eef43ca8)

app-routing.module.ts

const routes: Routes = [
  ...
  { path: 'student/registration/:token', component: RegistrationsComponent },
  { path: 'student/:token', component: GuidelinesComponent },
  ...
];

guidelines.component.html

forwardToRegistration(): void {
  this.router.navigateByUrl('/student/registration/' + this.studentToken);
}

The URL is updating correctly in the browser, but the RegistrationComponent is not rendered.

Thank you for your help!

like image 528
sivakumm Avatar asked Nov 07 '22 06:11

sivakumm


2 Answers

I had the same issue, and figured it out. Maybe your cant see the content change because you dont have router-outlet tag in the app.component.html. The url will change the content of

<router-outlet></router-outlet>

so you should placed the router-outlet tag in the app.component.html.

like image 53
kin Avatar answered Nov 11 '22 11:11

kin


I solved it by listening to router changes in the component which should be refreshed.

Step 1. In app.component.ts: Navigate to component (orphan) and pass an object with a variable tableName.

this.router.navigate( ['/orphan', {table:tableName} ] );

Step 2. In orphan.component.ts, subscript to the observable to detect router changes and get the tableName from the snapshot object :

constructor( private route:ActivatedRoute, private router:Router) { 
      /* Listen for router events through the observable */
      router.events.subscribe( (data) => {
        // get the data from the snapshot
        this.tableName = this.route.snapshot.params.table;
      })
}

The component Orphan is now refreshed with the tableName value.

like image 34
Rob Lassche Avatar answered Nov 11 '22 12:11

Rob Lassche