首页 > 解决方案 > How to use angular router child routes to affect state

问题描述

Atm I am using Angular router. At the parent route, I have a component render with default state (tabIndex = 0).

Desired Behaviour: At a child route, I would like to be able to change the tabIndex state on the same component.

Options considered

1. Using data

I have successfully been able to differentiate paths by adding data and subscribing to the activatedRoute's children's data.

this.route.children.forEach(c => c.data.subscribe(cd => console.log(cd, 'child data'))

Angular router - empty data object for child routes

2. Using parameterization

Someone also suggested that I could use a parameterized subroute and do a regex match.

Routing module segment that defines relationship:

{
        path: 'parent-path/:id',
        component: MyComponent,
        children: [{
          path: ':child-path'
          component: MyComponent,
        }]
},

--

What's the best way to accomplish this?

Neither option feels particularly great, especially since I will have multiple levels of parent/child relationships. Does anyone have any advice or thoughts. I haven't been able to find any other meaningful options for this and I am new to ng, so any advice or thoughts would be appreciated!

标签: angularangular-router

解决方案


就个人而言,我喜欢使用服务在孩子和父母之间进行交流。

//sharedService.ts

 private _tabIndex$ = new Subject<number>();
 public tabIndex$ = this._tabIndex$.asObservable();

 ngOnDestroy():void {
     this._tabIndex$.complete();
 }

 setTabIndex(index: number): void {
     // validate it is a number

     this._tabIndex$.next(index);
 }

// 父组件.ts

private _destroy$ = new Subject<void>();
constructor(
   private _sharedService: SharedService
){
    this._sharedService.tabIndex$.pipe(
      takeUntil(this._destroy$)
    ).subscribe(index => // do something);
}

ngOnDestroy():void {
    this._destroy$.next();
    this._destroy$.complete();
}

// 孩子

constructor(
 private _sharedService: SharedService,
 private _route: ActiveRoute
){
  const tabIndex = this._route.snapshot.data.tabIndex || null;
  if(tabIndex != null){
     this._sharedService.setTabIndex(tabIndex);
  }
}

子组件将自己发送 tabIndex。

此代码可以放在通用组件类中并扩展将发送其 tabIndex 的每个组件,因此您不必在每个组件中添加此代码。


推荐阅读