27

我有像这样的网址

  • www.yoursite.com/accounts/:accountid/info
  • www.yoursite.com/accounts/:accountid/users等等

accountidURL 中有一个整数值

但无法使用ActivatedRoute参数访问它。

现在我正在拆分 URL 以获取accountid

除了拆分 URL 之外,还有更好的方法来访问该值吗?

更新

我有一个不同的模块account,其中包括帐户相关页面的所有组件和服务。

我懒加载这个模块。所以在根级路由中,app-routing我指定

{ path:'account', loadChildren : './account/account.module#AccountModule' }

在帐户模块中account-routing,我指定孩子

path: 'account/:accountid', component: AccountComponent, canActivate: [AuthGuard],
    children: [
      { path: '', redirectTo: 'info', pathMatch: 'full' },
      { path: 'info', component: InfoComponent },
      { path: 'users, component: UsersComponent }
      {path: '**', redirectTo: 'info'}
    ]

笔记 :

如果存在,我们可以访问子路径中的参数。但不是父级的,为什么?

我正在获取undefined父路径中的参数

4

6 回答 6

62

在这篇文章的帮助下,问题得到了解决。

为了访问params父路由,我们需要使用activeRoute.parent.params 而不是activeRoute.params

this.activatedRoute.parent.params.subscribe(
    (params) => 
    { 
                 console.log(params.accountid); 
     });

同样从这个 stackoverflow question中,找到了使所有参数(包括父路由参数)可用于子路由的解决方案。

这是通过包含一个配置对象来完成的,该对象paramsInheritanceStrategy设置为always我们导入的位置RouterModule

例如:

import {RouterModule, ExtraOptions} from "@angular/router";

export const routingConfiguration: ExtraOptions = {
  paramsInheritanceStrategy: 'always'
};

export const Routing = RouterModule.forRoot(routes, routingConfiguration);

现在我们可以使用访问父子路由参数 activeRoute.params

于 2019-03-29T07:14:52.737 回答
7

试试这个解决方案:

 this.activatedRoute.params.subscribe(params => {
        const accountid= params['accountid'];
    });

如果上述方法不起作用,您也可以试试这个。(从这里得到这个解决方案

this.router.parent.params.switchMap(params => {
  // params = { id: 1234 }
});
于 2019-03-29T06:09:14.830 回答
4

您只需要使用paramsInheritanceStrategy. 见https://angular.io/api/router/ExtraOptions

于 2021-07-24T21:22:48.770 回答
3

parent属性现已添加到路线中:

 this.route.parent.paramMap
                .subscribe(params => {
                    if (params.has('accountid')) {
                        this.'accountid'= params.get('accountid');
                    }
                });
于 2020-05-01T18:28:45.983 回答
1

尝试这个

在构造函数中创建ActivatedRoute的对象

constructor(private route: ActivatedRoute) {}

因此,一旦创建了对象,您将获得路由参数,例如

    let accountid = this.route.snapshot.params['accountid'];

    console.log(accountid);

或者

let accountid = this.activatedRoute.snapshot.paramMap.get('accountid');
console.log(accountid);

我希望这会有用。

于 2019-03-29T06:27:41.247 回答
-1

我认为您需要通过构造函数中的以下代码访问当前路由参数,

this.activeRoute.params.subscribe(params => {
     if(params['accountid']) {
         console.log(params['accountid'])  // use it where you need
     }
})
于 2019-03-29T06:09:51.977 回答