zoukankan      html  css  js  c++  java
  • Angular2学习笔记——在子组件中拿到路由参数

      工作中碰到的问题,特此记录一下。

      Angular2中允许我们以`path:idchildPath`的形式来定义路由,比如:

    export const appRoutes: RouterConfig = [{
        path: 'app/:id', component: AppComponent,
        children: [
            { path: 'share', component: AppShareComponent },
            { path: 'issue', component: AppIssueComponent },
            { path: 'version', component: AppVersionComponent },
            { path: 'usage', component: AppUsageComponent },
            { path: 'notification', component: AppNotificationComponent },
            { path: 'resource', component: AppResourceComponent },
            { path: 'comment', component: AppCommentComponent },
            { path: 'activity', component: AppActivityComponent },
            { path: 'retire', component: AppRetireComponent },
            { path: '', component: AppComponent }
        ]
    }];

      如果是在AppComponent中,很容易使用`ActivatedRoute`拿到当前路由获取参数:

    ngOnInit() {
            this.route.params.subscribe((params) => {
                this.createPies();
                this.onTopListFilterChange(params['id']);
            });
        };

      但如果是在`children`中指定的component要拿到路由参数就没那么容易了,这时候再使用ActivatedRoute根本拿不到参数,我猜应当是在Angular2中一个ActivatedRoute对应一级路由配置,所以我们需要找到父级路由,由父级路由去拿参数。这时我们需要借用Router类的routeState属性的parent方法:

    this.router.routeState.parent(this.activatedRoute).params.subscribe(params => {
       this.getDetailsById(params['id']);
    })

      至此问题解决!

      Angular2给我的感觉是大框架很清晰,细节太琐碎,使用后端开发思维来做前端,过于冗余。目前对Angular2了解并不深入,无法给出详细解释,待我深入了解后,再写一篇关于路由的文章奉献给大家。

  • 相关阅读:
    15、常量指针和指针常量区别?
    14、strlen和sizeof区别?
    12、变量声明和定义区别?
    10、宏定义和函数和typedef有何区别?
    hdoj--1495--非常可乐(搜索+隐式图)
    hdoj--2579--Dating with girls(2)(搜索+三维标记)
    poj--3630--Phone List(字典树+前缀判断)
    poj--2001--Shortest Prefixes(字典树)
    Huatuo's Medicine
    hdoj--2803--The MAX(水题)
  • 原文地址:https://www.cnblogs.com/dojo-lzz/p/5883408.html
Copyright © 2011-2022 走看看