订阅activatedRoute,params有不同的属性来保存传递的param值

subscribing to activatedRoute, params has different attributes to hold the param value passed

在 targetComponent 中订阅的参数:

import Router from @angular/Router

  export class TargetComponent {
     constructor(private activeRoute: ActivatedRoute) {
       this.activeRoute.params.subscribe(params => {

       console.log(params)   // receives targetName but with different attributes
       console.log(params.name);   // sometimes params has attribute name 
       console.log(params.target); // and sometimes target 

  });

  }
}

从 firstComponent 发送参数

import ActivatedRoute from @angular/Router

this.router.navigate(['/', 'search' , targetName]);

从第二个组件发送参数

this.router.navigate(['/', 'table', targetName]);

路由配置

const routes: Routes = [
  {
    path: '',
    redirectTo: 'welcome',
    pathMatch: 'full'
  },
  {
    path: 'search/:name',
    component: SearchItemComponent
  },
  {
    path: 'table/:target',
    component: TableDataComponent
  }
 ]

试图理解为什么 params 对象会有 'target' 属性,有时 'name' 在从不同组件导航时存储值。

我假设您正在使用与 Angular 的 RouterModule 类似的东西?

我能想到的一件事是其中的某些代码是重复的,并且某些路线有到达目的地的迂回方式。

例如,您可能会看到如下代码:

const routes: Routes = [
      { path: 'target/:name', component: TargetComponent, canActivate: [AuthGuard]},
      { path: 'target/:target', component: TargetComponent}  
]

':' 后面的值是激活路由参数名称的决定因素(在本例中为 'name' 或 'target')。因此,如果您尝试访问 target/name,但 canActivate returns 为假,它将转到 target/target。实际上,没有任何改变,但参数的名称显然会有所不同,尽管值不会(具体来说,您可以访问 params.target,但不能访问 params.name)。

附加提示

需要注意的一件事是路由器实际上是从上到下的。因此,在类似的情况下,如果您将 Array 切换为如下所示:

const routes: Routes = [
      { path: 'target/:target', component: TargetComponent}, 
      { path: 'target/:name', component: TargetComponent, canActivate: [AuthGuard]} 
]

ActivatedRoutes 的参数名称将始终是 'target',因为没有 canActivate-Guard 可以阻止路由器访问该路由