Getting Parent Route Parameters in Angular 2 (Router v3.0.0-alpha.6)

Looking to create a site that uses one of Google’s recommended recommendations for multiregional and multilingual websites , in particular the model for using subdirectories with gTLD (for example, www.stackoverflow.com/en/questions/ask, www.stackoverflow.com/fr/questions / ask, etc.).

Depending on the top-level subdirectory, I would like to set the default language and get the corresponding JSON data. To explain when a user goes directly to www.mywebsite.com/en/home , the default language will be set to enand my content service will receive en.json.

In the above example, my routes will be configured like this:

export const routes: RouterConfig = [
  { path: ':country',          component: Home },
  { path: ':country/home',     component: Home },
  { path: ':country/about',    component: About },
  { path: ':country/contact',  component: Contact }
];

I am trying to understand how to capture the route parameter :country(if the URL is www.mywebsite.com/en/about/ I am trying to get the value of :countrythe route parameter en) in the component Home, Aboutor Contact. Here are some things I've tried:

export class Home implements OnInit {
    constructor(
        private route: ActivatedRoute
    ) {}

    private sub: any;

    ngOnInit(){
       this.sub = this.route.params.subscribe(params => {
         let country = params['country'];
         console.log(country) // undefined :(
       });
    }
}

I also tried using route.snapshotas follows:

export class Home implements OnInit {
    constructor(
        private route: ActivatedRoute
    ) {}

    ngOnInit(){
        let country = this.route.snapshot.params['country'];
        console.log(country) // undefined :(
    }
}  

We also tried to work with this solution to no avail: Angular 2 access parent routing files from a child component

If anyone has an idea for a different approach, please share!

+4
source share
1 answer

, , , :

import {Component, OnInit}              from '@angular/core';
import { Router, ActivatedRoute }       from '@angular/router';

@Component({
  selector: 'home',
  template: '<h1>Home: {{country}}</h1>'
})

export class HomeComponent implements OnInit {

  country: string;

  constructor(
    private route: ActivatedRoute,
    private router: Router) {

    this.country = '?';

  }

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       let country = params['country'];
       this.country = country;
       console.log(country);
     });
  }


}

, Home:, /en Home: en /fr - Home:fr. "about".

. : - (plunker).

+5

All Articles