如何使用角度路由器子路由影响状态

时间:2019-08-02 15:08:45

标签: angular angular-router

Atm我正在使用Angular路由器。在父路线上,我有一个具有默认状态(tabIndex = 0)的组件渲染。

所需的行为:在子路由中,我希望能够更改同一组件上的tabIndex状态。

考虑的选项

1。使用数据

通过添加data并订阅了ActivateRoute的子级数据,我已经成功地区分了路径。

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

Angular router - empty data object for child routes

2。使用参数化

有人还建议我可以使用参数化的子路由并进行正则表达式匹配。

定义关系的路由模块段:

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

-

什么是最好的方法?

这两种选择都不感觉特别好,特别是因为我将拥有多个级别的父母/孩子关系。有没有人有任何建议或想法。我还没有找到其他有意义的选择,而且我是ng的新手,所以任何建议或想法都将不胜感激!

1 个答案:

答案 0 :(得分:0)

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

// 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);
 }

// parentComponent.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的每个组件,因此您不必在每个组件中都添加此代码。