Angular:获取父路由中参数的值

42

我有类似以下的URL:

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

URL中有一个整数值accountid,但无法使用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的参数。


你可以使用路由“快照”方法,而不是使用“observable”方法。 - Bhagwat Tupe
10个回答

90
通过这篇文章的帮助,问题得以解决。
要访问父路由中的params,需要使用activeRoute.parent.params而不是activeRoute.params
this.activatedRoute.parent.params.subscribe(
    (params) => 
    { 
                 console.log(params.accountid); 
     });

另外,这个stackoverflow问题中找到了一种解决方案,可以使所有参数(包括父路由参数)对子路由可用。

方法是在导入RouterModule时,包含一个配置对象,并将paramsInheritanceStrategy设置为always

例如:

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

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

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

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


17

2
在 Angular 14 上对我很有效。 - Him Hah
这应该是正确的答案。在Angular 15上仍然完美运行。 - Gui Brunow

8

试试这个解决方案:

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

如果上述方法不起作用,您也可以尝试以下方法。(从这里获得的解决方案
this.router.parent.params.switchMap(params => {
  // params = { id: 1234 }
});

感谢回答。我已经尝试过这个方法,但在我的情况下不起作用。我已经更新了问题,包含更多细节。 - jophab
@Seba Cherian,这里的accountid是“路由参数”,而不是“查询参数”,所以我认为你的解决方案无法获取accountid的值。 - Nirali
如果这个答案解决了您的问题,请考虑将此答案/有效的答案标记为已接受(打勾)。 - Seba Cherian
从Angular 5开始,您可以使用paramsInheritanceStrategy。无需订阅父路由。 - Vugar Abdullayev

4
现在路由中添加了parent属性:
 this.route.parent.paramMap
                .subscribe(params => {
                    if (params.has('accountid')) {
                        this.'accountid'= params.get('accountid');
                    }
                });

1

私有路由:ActivatedRoute

this.route.snapshot.parent.params['accountid'])


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

我希望这会有所帮助。


2
如果您正在尝试获取父路由中的参数,就像OP所请求的那样,这种方法将无法正常工作。 - matt_lethargic

1

我需要从app-routing获取所有参数,所以这对我有用

this.route.firstChild?.params.subscribe((param) => {
      const accountId = param['account-id'];
});

编程愉快!


0

如果你在没有app.modules的情况下进行独立的main.ts编写,你可以使用withRouterConfig

bootstrapApplication(AppComponent, {
  providers: [
    // https://this-is-angular.github.io/angular-guides/docs/standalone-apis/configuring-the-router-using-standalone-features
    provideRouter(routes,
      withRouterConfig({paramsInheritanceStrategy: 'always'})
    ),
    ...

0
对于我的情况,我不得不向上追溯几代父母。
this._activatedRoute.parent.parent.snapshot.paramMap.get('id')

-1

我认为你需要通过以下代码在构造函数中访问当前路由参数:

this.activeRoute.params.subscribe(params => {
     if(params['accountid']) {
         console.log(params['accountid'])  // use it where you need
     }
})

谢谢你的回答。我已经尝试过这个方法了,但在我的情况下并没有起作用。我已经更新了问题,并添加了更多细节。 - jophab
@jophab请展示您使用此代码的实际代码! - Prashant Pimpale
@PrashantPimpale 我在 InfoComponent 的 ngOnInit() 中尝试了这段代码。对于 accountid,我得到了 undefined。当我尝试向子路由添加一个参数并使用相同的代码记录该参数时,它可以正常工作。但是对于父路径的参数,它无法正常工作。 - jophab
@jophab,你能提供 Stackblitz 吗? - Prashant Pimpale
如果您尝试从父路由获取参数,则此方法无效。 - matt_lethargic

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接