Can't get active route params

Viewed 588

I can not get active route parameters. When I console log I just get this enter image description here. This demo code stackblitz

Code

constructor(private route: ActivatedRoute) {
    this.route.params.subscribe((v) => {
      // this.params = v;
      console.log(v);
    })
    
  }

}

routing.module

const routes: Routes = [
  {
    path: '',
    component: PageComponent
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule],
})
1 Answers

That is because ActivatedRoute's "params" is only applicable when your route has an actual parameters being declared on your paths:

// So the parameter here is the ID
{ path: 'login/:id', component: HelloComponent },

you can declare any parameters in your route and any names you prefer

{ path: 'login/:userId', component: HelloComponent },

or 

{ path: 'login/:userId/:role', component: HelloComponent },

If you only want to get the current path without any extra parameters, you can implement it this way instead:

@Component({...})
export class TestComponent implements OnInit {

    constructor(private router: Router) {}    // Use Router instead of ActivatedRoute

    ngOnInit() {
      console.log(this.router.url);           // Get current route
                                              // if the url is "http://example.com/login" it will console /login
    }
    
}   
Related