本文介绍了如何以Angular方式在Angular2路线上获取参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

路线

const appRoutes: Routes = [
    { path: '', redirectTo: '/companies/unionbank', pathMatch: 'full'},
    { path: 'companies/:bank', component: BanksComponent },
    { path: '**', redirectTo: '/companies/unionbank' }
]

组件

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' },
        ]
    },
    ...
]

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

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

I want to get String bdo in the example link above.

我知道我可以通过使用window.location.href并将其拆分为数组来获取链接.因此,我可以获取最后一个参数,但是我想知道是否有适当的方法以角度方式执行此操作.

I'm aware that I can get the link by using window.location.href and split into array. So, I can get the last param but I want to know if there's a proper method on doing this in angular way.

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

Any help would be appreciated. Thanks

推荐答案

更新:2019年9月

正如少数人所提到的,应使用通用的Map API访问paramMap中的参数:

Update: Sep 2019

As a few people have mentioned, the parameters in paramMap should be accessed using the common MapAPI:

要获取这些参数的快照,可以在不关心它们可能会更改的情况下进行:

To get a snapshot of the params, when you don't care that they may change:

this.bankName = this.route.snapshot.paramMap.get('bank');

要订阅并收到有关参数值更改的警报(通常是由于路由器的导航)

To subscribe and be alerted to changes in the parameter values (typically as a result of the router's navigation)

this.route.paramMap.subscribe( paramMap => {
    this.bankName = paramMap.get('bank');
})

更新:2017年8月

自Angular 4起,不推荐使用params,而是使用新界面 paramMap .如果您仅用一个替换另一个,则上述问题的代码应该可以工作.

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.

如果在组件中注入ActivatedRoute,则可以提取路径参数

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"

这篇关于如何以Angular方式在Angular2路线上获取参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-17 14:06
查看更多