加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs – 在Angular 2中获取父路由参数(路由器v3.0.0-alpha.

发布时间:2020-12-17 17:26:35 所属栏目:安全 来源:网络整理
导读:希望使用 Google’s recommended practices for multi-regional and multilingual websites之一建立站点,特别是利用gTLD的子目录模型(例如www.stackoverflow.com/en/questions/ask,www.stackoverflow.com/fr/questions/ask等). 根据顶级子目录,我想设置默认
希望使用 Google’s recommended practices for multi-regional and multilingual websites之一建立站点,特别是利用gTLD的子目录模型(例如www.stackoverflow.com/en/questions/ask,www.stackoverflow.com/fr/questions/ask等).

根据顶级子目录,我想设置默认语言并获取相应的JSON数据.进一步解释,当用户直接导航到www.mywebsite.com/en/home时,默认语言将设置为en,我的内容服务将获取en.json文件.

在上面的示例中,我的路由将配置如下:

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

我想在Home,About或Contact组件中弄清楚如何获取:country route参数(如果URL是www.mywebsite.com/en/about/我正在尝试获取en的:country route参数值).这是我尝试过的几件事:

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 :(
       });
    }
}

我也尝试过使用route.snapshot,如下所示:

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

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

也试过使用这个解决方案无济于事:Angular 2 access parent routeparams from child component

如果有人对另一种方法有所了解请分享!

解决方法

我不确定为什么这对你不起作用,但我只是尝试了以下代码对我有用:

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.它对“约”页面的工作方式类似.

完整的来源是here.
更新:here is also live demo (plunker).

资源:

> Angular guide – Routing & Navigation
> Routing plunker example
> Angular Router post by Victor Savkin

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读