Ricardo Rocha
Ricardo Rocha

Reputation: 16206

Angular Routing: Passing dynamic url data to components

I have the following routes:

const routes: Routes = [
    {
        path: ':product/new',
        children: [{
            path: 'std/:country',
            component: SignUpComponent,
            data: {
                animation: 'animate',
                segment: 'std',
                country: ':country'
            }
        }, {
            path: 'exp/:country',
            component: PaymentComponent,
            data: {
                animation: 'animate',
                segment: 'exp'
            }
        }
    }
]

Is country: ':country' the right way of passing dynamic url data to the SignUpComponent? If yes, How can I consume this data in my SignUpComponent Component?

Upvotes: 0

Views: 1256

Answers (4)

dasunse
dasunse

Reputation: 3079

You do not need to pass this way country: ':country'. By using this way you can read path variables

import {  ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute) {
  alert(route.snapshot["data"].country)
}

Upvotes: 1

Adrita Sharma
Adrita Sharma

Reputation: 22213

Try like this:

WORKING DEMO // click on Home

import { ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute) {
  alert(route.snapshot["data"].country)
}

Upvotes: 1

Michael Desigaud
Michael Desigaud

Reputation: 2135

You do not need the country property in the data object. The country info in the url should be enough.

To retrieve the country parameter from the route :

class  SignUpComponent implements OnInit {
  constructor(private activatedRoute: ActivatedRoute) {}
  ngOnInit() {
    this.activatedRoute.params.subscribe((params) => {
        // params.country should be defined here    
    });
 }
}

Upvotes: 1

Athanasios Kataras
Athanasios Kataras

Reputation: 26342

In your constructor

public constructor(private route:ActivatedRoute, private router:Router) {
      console.log(route.snapshot.data['country']);
  }

Or you can use the following as per documentation from the router outlet (check here)

export class AppComponent {
  getCountryData(outlet: RouterOutlet) {
    return outlet && outlet.activatedRouteData && outlet.activatedRouteData['country'];
  }
}

Upvotes: 0

Related Questions