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

jop*_*hab 20 angular angular-activatedroute

我有这样的网址

  • 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' }
Run Code Online (Sandbox Code Playgroud)

在帐户模块的 中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'}
    ]
Run Code Online (Sandbox Code Playgroud)

笔记 :

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

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

jop*_*hab 48

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

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

this.activatedRoute.parent.params.subscribe(
    (params) => 
    { 
                 console.log(params.accountid); 
     });
Run Code Online (Sandbox Code Playgroud)

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

这是通过包括与配置对象进行paramsInheritanceStrategy设置,以always我们的进口,其中RouterModule

例如:

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

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

export const Routing = RouterModule.forRoot(routes, routingConfiguration);
Run Code Online (Sandbox Code Playgroud)

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

  • 谢谢!我不知道 paramsInheritanceStrategy 存在! (2认同)

Vug*_*yev 19

您所需要的只是使用paramsInheritanceStrategy. 请参阅https://angular.io/api/router/ExtraOptions

  • 在 Angular 14 上对我来说工作得很好。 (2认同)

Seb*_*ian 7

试试这个解决方案:

 this.activatedRoute.params.subscribe(params => {
        const accountid= params['accountid'];
    });
Run Code Online (Sandbox Code Playgroud)

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

this.router.parent.params.switchMap(params => {
  // params = { id: 1234 }
});
Run Code Online (Sandbox Code Playgroud)