Jon*_*ark 5 angular-routing angular angular-activatedroute
我正在构建一个Angular 7应用程序.在这个应用程序中,我得到了嵌套路线.我希望能够检测父路由使用的组件.我找到了一种在本地进行的方法,但这对生产无效(输出不同).
我用这个方法:
checkIfChild() {
this.sub = this.route.parent.params.subscribe(params => {
if (params['id']) {
this.parentId = params['id'];
if (this.route.parent.component['name'] === 'ProjectShowComponent') {
this.parentType = 'Project';
} else if (this.route.parent.component['name'] === 'CompanyShowComponent') {
this.parentType = 'Company';
} else if (this.route.parent.component['name'] === 'ContactShowComponent') {
this.parentType = 'User';
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
方法this.route.parent.component ['name']在本地输出名称,但在生产时只输出字母T.
我收到了这条消息
TypeError: 'arguments', 'callee', and 'caller' cannot be accessed in this context.
Run Code Online (Sandbox Code Playgroud)
什么是检测父路线激活子路线的正确方法,以便我可以采取行动?
就我个人而言,我会放弃与组件实例的直接耦合,而是使用data路由的属性,考虑到:
假设以下路由定义:
const routes: Routes = [
{
path: 'production',
component: ProductionParent,
data: {parentRoute :'Production'},
children: [{path: '', component: Child}]
},
{
path: 'system',
component: SystemParent,
data: {parentRoute :'System'},
children: [{path: '', component: Child}]
}
];
@Component({})
export class ProductionParent{}
@Component({})
export class SystemParent{}
@Component({})
export class Child implements OnInit, OnDestroy {
private parentSub = Subscription.EMPTY;
parentRoute :string;
constructor(private readonly route: ActivatedRoute){}
ngOnInit(){
this.trackParent();
}
ngOnDestroy(){
this.parentSub.unsubscribe();
}
private trackParent(){
this.parentSub = this.route.parent
.data
.subscribe(data => this.parentRoute = data.parentRoute || 'unknown');
}
}
Run Code Online (Sandbox Code Playgroud)
这很可能可以通过其他方式实现,但这是我想到的第一个务实的方法。希望能帮助到你。
| 归档时间: |
|
| 查看次数: |
446 次 |
| 最近记录: |