【问题标题】:How to use angular router child routes to affect state如何使用角度路由器子路由来影响状态
【发布时间】:2019-08-02 15:08:45
【问题描述】:

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

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

考虑的选项

1.使用数据

我已经成功地通过添加data 并订阅activatedRoute 的子数据来区分路径。

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 新手,所以任何建议或想法都将不胜感激!

【问题讨论】:

  • “tabIndex 状态”是什么意思
  • 组件上有一个 tabindex 状态,它决定了哪个 当前处于活动状态。但还有其他用例,我只是想提供一个示例。

标签: angular angular-router


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 2020-02-08
    • 1970-01-01
    • 2016-09-09
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多