更新
在评论中讨论后,我的答案将是下一个:尽一切ngOnInit
努力避免在这里和那里传递变量的复杂性。
ngOnInit(): void {
this.data$ = this.store$.select(Selectors.selectMoreData, this.viewName);
this.store$.dispatch(Actions.loadView());
}
或者在router-store
ngOnInit(): void {
this.data$ = this.store$.pipe(
select(selectRouteParam('viewName')),
switchMap(viewName => combineLatest([
of(viewName),
this.store$.select(Selectors.selectMoreData, this.viewName)),
]),
map(([viewName, data]) => ({viewName, data}));
);
this.store$.dispatch(Actions.loadView());
}
并在模板中
<ng-container *ngIf="data$ | async as data">
<child [view]="data.viewName" [data]="data.data"></child>
</ng-container>
或者在this.activatedRoute
ngOnInit(): void {
this.data$ = this.activatedRoute.paramMap.pipe(
map(params => params.get('viewName')),
switchMap(viewName => combineLatest([
of(viewName),
this.store$.select(Selectors.selectMoreData, this.viewName)),
]),
map(([viewName, data]) => ({viewName, data}));
);
this.store$.dispatch(Actions.loadView());
}
原来的
您错过了第三个选项 - 要使用将为您的组件提供数据的解析器ActivatedRoute.data
,您可以在此处的答案中找到一个示例:https ://stackoverflow.com/a/61836566/13112018 。
再说回viewName
。您可以将其添加为路线的数据,然后也可以访问它router-store
。
例如,您可以定义这样的路线。
{
path: 'test',
component: TestComponent,
data: {
viewName: 'test',
},
},
然后用来router-store
选择它
this.store.select(selectRouteData).subscribe(console.log); // {viewName: 'test'}