第一步:
想象一下,项目中某处有一个名为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的最有效方法是什么,以便我动态地执行一些操作?
如果没有经过验证的(最先进的)方法,我如何从第一步到第二步?
我可以完全省去第二步,更优雅地进入第三步吗?
Edit1:
Btw:forkJoin
不能以这种方式与路线(ActivatedRoute)可观察物一起使用,因为路线可观察物未完成。以下方法可行,但我的问题仍然存在:
// excerpt!
// routeData is a public property
ngOnInit() {
this.getAllRouteData();
}
getAllRouteData() {
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;
forkJoin(
state$.pipe(first()),
url$.pipe(first()),
params$.pipe(first()),
queryParams$.pipe(first()),
fragment$.pipe(first()),
data$.pipe(first())
).subscribe(
(routeData: any) => {
this.routeData = routeData;
this.start();
},
(error: any) => {
console.log('Error: ', error);
}
);
}
Edit2:当前解决方法(routeObservables
不能在其他组件中真正重用)
getAllRouteData() {
const routeObservables = [
this.route.paramMap.pipe(map(() => window.history.state)),
this.route.url,
this.route.params,
this.route.queryParams,
this.route.fragment,
this.route.data
];
forkJoin(routeObservables.map(r => r.pipe(first()))).subscribe(
(routeData: any) => {
this.routeData = routeData;
}
);
}
我为什么要问?
[我最大的问题是“单一责任”,我试图避免复制+粘贴代码(例如,每个组件中的routeObservables
以上,都需要与路线相关的数据)。
const keys = Object.keys(this.RouteObservables);
const sources = this.keys.map(key => this[this.RouteObservables.key]);
forkJoin(...this.sources).subscribe(
(routeData: any) => {
this.routeData = routeData;
}
);
ps.s。类必须在其构造函数中注入this.route
。尚未测试,但我认为这应该可以解决问题。让我知道是否有任何错误。