Frank
Frank

Reputation: 2431

ActivatedRoute.snapshot.paramMap not working

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

Upvotes: 6

Views: 4358

Answers (2)

Temo Kiknadze
Temo Kiknadze

Reputation: 367

try this:

this.router.parseUrl(this.router.url).queryParams['coupon']

Upvotes: 2

Naren Murali
Naren Murali

Reputation: 56650

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.

Stackblitz example

Upvotes: 5

Related Questions