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?
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:
The first instance of
AppComponent
instantiated by the framework during the bootstraping step will be used as root component, and as a consequence, the injectedActivatedRoute
will be sort of "disconected" from that route definition of yours.Furthermore, instances of
AppComponent
resolved through theRouterOutlet
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 ofAppComponent
wont reflect the route parameters in neither async or sync manner. If you navigate to something like{url}/#/bla
, a second instance ofAppComponent
will be resolved because of the<router-outlet>
. TheActivatedRoute
instance inject into it will reflect the route parameter values, both sync. and asynchronously.