hosein dafeyan
hosein dafeyan

Reputation: 117

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.

Upvotes: 1

Views: 3685

Answers (2)

Sachin Gupta
Sachin Gupta

Reputation: 5301

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

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

Upvotes: 1

Jamie Rees
Jamie Rees

Reputation: 8183

You can access the data by accessing the route's snapshot like the following:

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

So you can do the above instead of subscribing to the observable

Upvotes: 0

Related Questions