Angular 8/9-(动态订阅):如何在从集合中获取Observable时自动forkJoin?

问题描述 投票:1回答: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的最有效方法是什么,以便我动态地执行一些操作?

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

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

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以上,都需要与路线相关的数据)。

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

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

尚未测试,但我认为这应该可以解决问题。让我知道是否有任何错误。

© www.soinside.com 2019 - 2024. All rights reserved.