簡體   English   中英

如何從Angular2中的父組件獲取子路由的id參數

[英]How to get :id param of child route from parent component in Angular2

我正在嘗試獲取:id定義的參數

RouterModule.forRoot([
  {
    path: 'orders',
    component: ListComponent,
    children: [
      {
        path: 'view/:id',
        component: ViewComponent
      },
    ]
  }
])

ListComponent

我已經嘗試過:

route: ActivatedRoute

route.params.subscribe(params => {
  let id = +params['id'];
})

來自ListComponent ,但params數組是空的,我想這是因為:id param 屬於ViewComponent而不是ListComponent

如何在ListComponent獲取id參數?

您可以使用firstChild屬性或ActivatedRoute來獲取子路由:

route.firstChild.snapshot.params['id']

為了在父組件中獲取子組件的參數,我使用了 ActivatedRoute 的 firstChild 屬性,因為我只有子路由

route: ActivatedRoute

route.firstChild.params.subscribe(params => {
  let id = +params['id'];
});

遞歸查找子參數並不總能得到您正在尋找的參數。 特別是在移動路線時。

相反,可以使用 RxJS ReplaySubject來發布當前子 ID。

創建一個新服務:

@Injectable()
export class ChildIdService  {
  current$ = new ReplaySubject<number>();
}

將其導入子組件並訂閱重放主題:

export class ChildComponent implements OnInit {
  constructor(private ar: ActivatedRoute, public ci: ChildIdService){}

  ngOnInit(){
    this.ar.params.map(params => +params.id).subscribe(this.ci.current$);
  }
}

在父組件上導入服務並使用異步管道訂閱子值:

<span>Mother component child ID: {{ci.current$ | async}}</span>

這是一個工作片段: https : //stackblitz.com/edit/angular-b8xome (將 /child/42 添加到瀏覽器應用程序預覽中以查看它的工作情況)


或者將組件定義為兄弟組件並將父組件添加為無組件路由,例如: https : //vsavkin.com/the-powerful-url-matching-engine-of-angular-router-775dad593b03在“使用相同數據的兄弟組件”下”

如果只有一個子路由,您可以繼續挖掘route.firstChild.params['id']或使用類似route.children[0].children[1].params['id']的東西挖掘多個使用括號表示法訪問同級路由的級別。 在找到正確的級別時,它有點反復試驗。

另一種方法是在父組件中添加以下內容:

<ng-container *ngIf="routerOutlet.isActivated && routerOutlet.activatedRoute?.paramMap | async as paramMap">
child id is: {{paramMap.get('id')}}!
</ng-container>

<router-outlet #routerOutlet="outlet"></router-outlet>

當然,在孩子使用解析器而不是參數會更好

<ng-container *ngIf="routerOutlet.activatedRouteData['child'] as child">
child id is : {{child.id}}
</ng-container>

<router-outlet #routerOutlet="outlet"></router-outlet>

假設子路線有類似的東西:

// ...
resolve: {
 child: 'childResolver',
},

並且子解析器可以在某個模塊中:

// ...
providers: [{
    provide: 'childResolver',
    useValue: (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) => ({
      id: route.paramMap.get('id')
    })
  }],

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM