如何以Angular方式获取Angular2路径上的参数?

dev*_*una 62 angular2-routing angular

路线

const appRoutes: Routes = [
    { path: '', redirectTo: '/companies/unionbank', pathMatch: 'full'},
    { path: 'companies/:bank', component: BanksComponent },
    { path: '**', redirectTo: '/companies/unionbank' }
]
Run Code Online (Sandbox Code Playgroud)

零件

const NAVBAR = [
    { 
        name: 'Banks',
        submenu: [
            { routelink: '/companies/unionbank', name: 'Union Bank' },
            { routelink: '/companies/metrobank', name: 'Metro Bank' },
            { routelink: '/companies/bdo', name: 'BDO' },
            { routelink: '/companies/chinabank', name: 'China Bank' },
        ]
    },
    ...
]
Run Code Online (Sandbox Code Playgroud)

链接示例: http://localhost:8099/#/companies/bdo

我想 在上面的示例链接中获取String bdo.

我知道我可以通过使用window.location.href获取链接并拆分成数组.所以,我可以得到最后一个参数,但我想知道是否有一个正确的方法以角度方式这样做.

任何帮助,将不胜感激.谢谢

Bee*_*ice 140

如果您注入paramMap组件,您将能够提取路径参数

this.bankName = this.route.snapshot.paramMap.get('bank');
Run Code Online (Sandbox Code Playgroud)

如果您希望用户直接从一个银行导航到银行,而不先导航到另一个组件,您应该通过一个observable访问该参数:

this.route.paramMap.subscribe( paramMap =>
    this.bankName = paramMap.get('bank');
)
Run Code Online (Sandbox Code Playgroud)

对于文档,包括两者之间的差异,请查看此链接并搜索" activatedroute "

更新:2017年8月

自Angular 4以来,Map已经弃用了新界面params.如果您只是将一个替换为另一个,则上述问题的代码应该有效.


KMJ*_*sen 17

从Angular 6+开始,处理方式与以前的版本略有不同.正如@BeetleJuice在上面答案中提到的,paramMap是获取路径参数的新接口,但是在更新版本的Angular中执行有点不同.假设这是在一个组件中:

private _entityId: number;

constructor(private _route: ActivatedRoute) {
    // ...
}

ngOnInit() {
    // For a static snapshot of the route...
    this._entityId = this._route.snapshot.paramMap.get('id');

    // For subscribing to the observable paramMap...
    this._route.paramMap.pipe(
        switchMap((params: ParamMap) => this._entityId = params.get('id'))
    );

    // Or as an alternative, with slightly different execution...
    this._route.paramMap.subscribe((params: ParamMap) =>  {
        this._entityId = params.get('id');
    });
}
Run Code Online (Sandbox Code Playgroud)

我更喜欢使用两者,因为在直接页面加载时我可以获得ID参数,并且如果在相关实体之间导航,则订阅将正确更新.

Angular Docs中的来源

  • @crush 来自上面链接的文档:“您可能想使用 RxJS `map` 运算符。但是 `HeroService` 返回一个 `Observable<Hero>`。因此,您可以使用 `switchMap` 运算符将 Observable 展平。` switchMap 操作符也会取消之前的请求。如果用户使用新的 id 重新导航到这条路由,而 HeroService 仍在检索旧的 id ,则 switchMap 丢弃旧请求并返回新`id`的英雄。” (4认同)

use*_*367 5

这个主题已经很老了,但仍然位于我的搜索引擎结果之上。我非常确定这里展示的方法已经有效。但其中一些已经过时或不完整。这是一个最新的完整示例,希望对您有所帮助。我将参数接收组件称为PersonComponent。第一部分是您的路由最有可能在app.module.ts (app-routing.module.ts)中定义:

const routes: Routes = [
{path: "/", component: HomeComponent}, 
{path: "person/name/:personName", component: PersonComponent}];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {
}
Run Code Online (Sandbox Code Playgroud)

注意PersonComponent 路径中的:personName ,这是我们必须寻找的键,您可以随意称呼它。接下来在另一个(或相同)组件的 HTML 部分中使用此路由:

<a routerLink="person/name/Mario">This is Mario</a>
<a routerLink="person/name/Luigi">This is Luigi</a>
<a routerLink="person/name/Bowser">This is Bowser</a>
Run Code Online (Sandbox Code Playgroud)

这里:personName被替换为实际名称。最后一个是在PersonComponent中读取这个参数

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

@Component({
  selector: 'app-person',
  templateUrl: './person.component.html',
  styleUrls: ['./person.component.scss']
})
export class PersonComponent {

  constructor(route: ActivatedRoute) {
    const name = route.snapshot.paramMap.get('personName');
    console.log(name)
    //do whatever you want with it
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以看到路由中的:personName用作键,以从paramMap获取值。