((动态订阅):如何在从集合中获取Observable的同时自动forkJoin?

问题描述 投票:0回答:1

第一步:

想象一下,项目中某处有一个名为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的最有效方法是什么,以便我动态地执行一些操作?

  • 如果没有经过验证的(最先进的)方法,我如何从第一步到第二步?

  • 我可以完全省去第二步,更优雅地进入第三步吗?

angular typescript dynamic rxjs6 fork-join
1个回答
0
投票
所以主要问题是您有字符串值,需要将它们用作Javascript对象,对吗?在这种情况下,可以使用方括号访问以下属性:

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
© www.soinside.com 2019 - 2024. All rights reserved.