首页 > 解决方案 > 访问子路由:id

问题描述

我有一个子组件及其父组件。子组件包含以下管道来订阅激活的路由:

this.route.paramMap.pipe(
  map(paramMap => +paramMap.get('id')),
  switchMap((id: number) => this.apiService.getTasks(id.toString())),
).subscribe(tasks => this.tasks = tasks);

{ path: '', component: DashboardComponent, children: [
      { path: '', redirectTo: '0', pathMatch: 'full' },
      { path: '0', component: NoListComponent },
      { path: ':id', component: ListComponent }
    ]},

如何在父组件内部访问此路由 :id DashboardComponent

我问是因为我需要在父母内部使用相同的 id。我已经尝试通过它,@ViewChild但这不会在路线更改时更新。

编辑:事件发射是不可能的,因为我正在使用路由器插座。

标签: angulartypescript

解决方案


通过router-outlet的父子组件通信是通过修改Parent组件的onActivate函数来实现的,如下:

onActivate(childComponent) {
    childComponent.someEventEmitter.subscribe((data) => {
    // Will receive the data from child here 
})

Child 组件照常创建 EventEmitter:

export class ChildComponent {
  @Output() someEventEmitter: EventEmitter<any> = new EventEmitter();

  someFunction(data) {
    // emit data to parent component
    this.someEventEmitter.emit(data);
  }
}

在html中:

<button type="button" (click)="someFunction()">Do Something</button>

推荐阅读