How to get parameter on Angular2 route in Angular way?

淺唱寂寞╮ 提交于 2019-11-28 04:49:38

If you inject ActivatedRoute in your component, you'll be able to extract the route parameters

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

constructor(private route:ActivatedRoute){}
bankName:string;

ngOnInit(){
    // 'bank' is the name of the route parameter
    this.bankName = this.route.snapshot.params['bank'];
}

If you expect users to navigate from bank to bank directly, without navigating to another component first, you ought to access the parameter through an observable:

ngOnInit(){
    this.route.params.subscribe( params =>
        this.bankName = params['bank'];
    )
}

For the docs, including the differences between the two check out this link and search for "activatedroute"

Update: Aug 2017

Since Angular 4, params have been deprecated in favor of the new interface paramMap. The code for the problem above should work if you simply substitute one for the other.

As of Angular 6+, this is handled slightly differently than in previous versions. As @BeetleJuice mentions in the answer above, paramMap is new interface for getting route params, but the execution is a bit different in more recent versions of Angular. Assuming this is in a component:

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');
    });
}

I prefer to use both because then on direct page load I can get the ID param, and also if navigating between related entities the subscription will update properly.

Source in Angular Docs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!