angular - 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!
解决方案
就个人而言,我喜欢使用服务在孩子和父母之间进行交流。
//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 的每个组件,因此您不必在每个组件中添加此代码。
推荐阅读
- javascript - 插入另一个项目后 actionEventListener ("click") 不起作用
- c# - 有没有办法将图像和字符串变量存储在一个数组中?(统一)
- django - Django Emailfield 固定后缀
- query-optimization - SPARQL DBPedia 查询座位容量、优化和删除重复项
- javascript - 为什么我的代码将提示发送到我的手机,而不是发送给尝试向机器人发送消息的任何其他人?
- arrays - Ada:添加新元素时修改数组长度
- django - Django如何按多个字段分组并求和
- php - PHP MVC - 所有控制器的一个视图类与每个控制器的视图类
- regex - 如何编写 unix 正则表达式以选择 cp for 循环中的特定文件
- c# - 有没有办法让我将 O'reilly 转换为 O'Reilly?