Unable to access a route parameter through route.snapshot in root component

3.1k views Asked by At

I want to get token from url but it return null as value.

app.component.ts:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {    
  constructor(private route: ActivatedRoute) { }

    ngOnInit(){  
    const token = this.route.snapshot.paramMap.get('token');
    console.log(token);

and routing.ts

{ path: ':token', component: AppComponent }

i want to grab contents after / in url eg: localhost:4200/content-to-grab any solutions?

4

There are 4 answers

1
Jota.Toledo On BEST ANSWER

Your approach is ok, there is another conceptual issue going on:

you are trying to associate a path to the root component.

Most likely, your root module looks like this:

@NgModule({
  imports: [
    RouterModule.forRoot(...)
  ],
  declarations:[
    ...
    AppComponent,
    ...
  ],
  boostrap: [AppComponent]
})
export class AppModule {}

The first instance of AppComponent instantiated by the framework during the bootstraping step will be used as root component, and as a consequence, the injected ActivatedRoute will be sort of "disconected" from that route definition of yours.

Furthermore, instances of AppComponent resolved through the RouterOutlet directive will be aware of your route definition.

You can check this by yourself in the following stackblitz.

The ActivatedRoute instance injected into the first instance of AppComponent wont reflect the route parameters in neither async or sync manner. If you navigate to something like {url}/#/bla, a second instance of AppComponent will be resolved because of the <router-outlet>. The ActivatedRoute instance inject into it will reflect the route parameter values, both sync. and asynchronously.

0
Celestin Bochis On

Try to grab it like this.

this.route.snapshot.params["token"]
0
madhukar reddy On
ngOnInit(){  
    const token = this.activatedRout.snapshot.params.token;
}
0
callback On

Change your code to

this.route.paramMap.subscribe(params => { console.log(params.get('token'));})