第一步:
想象一下,项目中某处有一个名为RouteObservables
的对象,我想在许多组件中使用(导入):
export const RouteObservables = {
state$: 'this.route.paramMap.pipe(map(() => window.history.state))',
url$: 'this.route.url',
params$: 'this.route.params',
queryParams$: 'this.route.queryParams',
fragment$: 'this.route.fragment',
data$: ' this.route.data'
};
第二步骤:
我想得到以下情况(通过使用上面的RouteObservables对象):
const state$ = this.route.paramMap.pipe(map(() => window.history.state));
const url$ = this.route.url;
const params$ = this.route.params;
const queryParams$ = this.route.queryParams;
const fragment$ = this.route.fragment;
const data$ = this.route.data;
第三步骤
我想使用相同的集合RouteObservables
自动启动forkJoin
:
forkJoin([...Object.keys(RouteObservables)]).subscribe(
(routeData: any) => {
this.routeData = routeData;
}
);
为什么需要RouteObservables
对象?
我需要有序的序列来访问正确的数据(例如routeData[0]
将是我的状态对象,有可能是从先前的路线转移过来的)。此对象帮助我也不要错过一些最终要取消订阅的订阅(ngOnDestroy
)。
我的问题:
在对象(或集合)中按顺序(我感兴趣)声明Observable的最有效方法是什么,以便我动态地执行一些操作?
如果没有经过验证的(最先进的)方法,我如何从第一步到第二步?
我可以完全省去第二步,更优雅地进入第三步吗?
const keys = Object.keys(this.RouteObservables);
const sources = this.keys.map(key => this[this.RouteObservables.key]);
forkJoin(...sources).subscribe(
(routeData: any) => {
this.routeData = routeData;
}
);
ps.s。类必须在其构造函数中注入this.route
。