Angular 2路由,如何访问网址

时间:2016-12-19 16:06:44

标签: angular url-routing angular2-routing

我正在构建一个应用程序,其中第一个url段代表界面的语言,例如:

/en/customer/3
/en/shop

我的路由器设置如下:

{ path: ':lang/customers/:id', component: CustomerComponent },
{ path: ':lang/shop', component: ShopComponent },

我想在引导的AppComponent或翻译服务中使用url(lang =' en'在本例中)中的语言参数。我可以在ShopComponent和CustomerComponent中访问此参数,但代码中没有其他地方。当我在AppComponent中输入它时:

constructor(private activatedRoute: ActivatedRoute, private router : Router) {
}

ngOnInit() {
  this.router.routerState.root.params.subscribe((params: Params) => {
    console.log('params: ',params);
  }
  this.activatedRoute.params.subscribe((params: Params) => {
    console.log('params: ',params);
  }
}      

我得到两个空对象。网址参数仍然是空的。

我做错了什么?也许更重要的是,我显然缺少对路由器的一些概念性理解,但我在文档或其他地方找不到任何有用的信息。

感谢您的帮助!

3 个答案:

答案 0 :(得分:8)

试着回答我自己的问题,我认为没有简单的方法按照我的想法去做。路由器设置如

{ path: ':lang/customers/:id', component: CustomerComponent } 

将整个路径附加到CustomerComponent,使lang和id成为可用参数。从这个角度来看,很清楚为什么在CustomerComponent之外无法访问这些参数。

我最终做的是重新定义我的路由器:

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';

import { LanguageComponent, CustomerComponent, ShopComponent } from "./";

@NgModule({
    imports: [
    RouterModule.forRoot([
      { path: ':lang', component: LanguageComponent ,
        children: [
          { path: 'shop', component: ShopComponent },
          { path: 'customer/:id', component: CustomerComponent },
          { path: '**', redirectTo: '/shop', pathMatch: 'full' }
        ]
      },
            { path: '**', redirectTo: '/en', pathMatch: 'full' }
    ])
  ],
  exports: [
    RouterModule
  ]
})
export class AppRoutingModule {}

然后我创建了一个LanguageComponent作为路由组件。

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

import { TranslateService } from './'
@Component({
  template : '<router-outlet></router-outlet>'
})
export class LanguageComponent implements OnInit {

  constructor( private activatedRoute : ActivatedRoute, private translateService: TranslateService) {
  }

  ngOnInit() {
    this.activatedRoute.params.subscribe( (params : Params) => {
      this.translateService.setLanguage( params['lang'] );
    });    
  }
}

然后我将语言存储在全球可用的TranslateService中。

答案 1 :(得分:1)

查看有关获取路线参数的this帖子

从路线获取参数

this.subscription = this.activatedRoute.params.subscribe(
 (param: any) => {
   let language = param['lang'];
   this.chosenLang = language; // Access to the lang
 });

在您想要获取路线参数的组件中

<强> app.component.ts

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

@Component({
  selector: 'my-app',
  template: `<blah></blah>`,
  styles: []
})
export class AppComponent implements OnInit, OnDestroy {
  private subscription: Subscription;
  chosenLang: string = "";

  constructor(private activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    // subscribe to router event
    this.subscription = this.activatedRoute.params.subscribe(
     (param: any) => {
       let language = param['lang'];
       this.chosenLang = language; // Access to the lang
     });
  }

  ngOnDestroy() {
    // prevent memory leak by unsubscribing
    this.subscription.unsubscribe();
  }

}

答案 2 :(得分:0)

这可能会做你想要的事情

constructor(router:Router) {
  router.events.filter(e => e instanceof NavigationEnd).subscribe(e => {
    console.log('lang', router.routerState.root.params['lang']);
  });
}

它应该在服务和组件中起作用。