angularangular-routingrouteparamsangular-activatedroute

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


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?


Solution

  • 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.