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

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

发布时间:2020-12-17 08:01:33 所属栏目:安全 来源:网络整理
导读:路线 const appRoutes: Routes = [ { path: '',redirectTo: '/companies/unionbank',pathMatch: 'full'},{ path: 'companies/:bank',component: BanksComponent },{ path: '**',redirectTo: '/companies/unionbank' }] 零件 const NAVBAR = [ { name: 'Banks
路线
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。

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

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

如果在组件中注入ActivatedRoute,则可以提取路径参数
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'];
}

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

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

对于文档,包括两个check out this link之间的差异并搜索“activatedroute”

更新:2017年8月

从Angular 4开始,params已被弃用,以支持新接口paramMap.如果您只是将一个替换为另一个,则上述问题的代码应该有效。

(编辑:李大同)

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

    推荐文章
      热点阅读