Search code examples
angularroutesangular-router

how to get data from url in Angular 7


I used the One component For many page in angular. I want to send a parameter from each component for show any different data. So I used the this code for call each component in Html:

<a  [routerLink]="['categories']" >Page1</a>
<a  [routerLink]="['categories']" >Page2</a>

Now in routes i Used this code

  {path:'Page1' ,component : ProductCategoriesPagesComponent ,data : {PageNo : 1}},
  {path:'Page2' ,component : ProductCategoriesPagesComponent,data : {PageNo : 2}}

Then I used this code in ProductCategoriesPagesComponent

ngOnInit() {
    this.route.data
        .subscribe(data => {
          console.log("data",data);
        });
}

But i get

data {}

In console. Please Help me how I get parameters from routes If I mistake, show the best way for this method. Thanks.


Solution

  • You need to inject ActivatedRoute and get the data from snapshot.

    this.activatedRoute.snapshot.data['PageNo'];