I trying to get a route param on startup/initial route. But it is not working.
app.component.ts
import { ActivatedRoute } from '@angular/router';
...
constructor(
private activatedroute: ActivatedRoute
) {}
ngOnInit() {
console.log(this.activatedroute.snapshot.paramMap.get('token'));
this.activatedroute.paramMap.subscribe( paramMap => {
console.log(paramMap.get('token'));
});
}
app.module.ts (includes more than just this though)
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
{ path: ':token', component: HelloComponent },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
Then I serve my app and go to:
http://localhost:4200/123
But my app.component.ts just console.log's null null
. Why is this not working? I feel like I have everything correct. Here is an Angular Blitz to work with: https://stackblitz.com/edit/angular-wnrrkd
you have written the code in app.component.ts
which is the root component, but the :token
is defined for the child component, so I have moved the code to the child component, one more thing to note is that in app.component.html
you need to have router outlet which will display the child component, only then the token will be visible, please refer the below example.