从forkJoin获取数据后才订阅Subject

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

我想将一些数据从一个模块传递到另一个模块。为此,我正在使用主题。我创建了以下主题:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SelectedClusterService {

  constructor() { }

  public selectedClusterName = new Subject<string>();

}

我正在通过上述服务从“oneComponent”传递一些数据,然后重定向到“anotherComponent”:

this.selectedClusterService.selectedClusterName.next(cluster_name);

并像这样将数据获取到“anotherComponent”:

this.selectedClusterService.selectedClusterName.subscribe(res => {
  this.selectedCluster = res;
  console.log("this.selectedCluster", this.selectedCluster);
});

这工作正常,我正在将数据发送到“另一个组件”。但在“anotherComponent”中我使用的是forkJoin。我只想在从 forkJoin 获取数据后才从 subject 获取数据。 我正在尝试这样:

   ngOnInit() {
    forkJoin([
      this.dataService.getUpgradeAppList(),
      this.dataService.getClusterList()
    ]).subscribe((data: any) => {
      console.log("forkJoin :: ngOnInit ::", data);
      this.appList = data[0].apps;
      this.clusterList = data[1];

    }); 
    this.selectedClusterService.selectedClusterName.subscribe(res => {
      this.selectedCluster = res;
      console.log("this.selectedCluster", this.selectedCluster);
    });
  }

我尝试过使用changeDetection

ngAfterViewInit
ngAfterContentChecked
,我也尝试使用
setTimeout
,但没有任何作用。我总是先获取主题数据,然后获取 forkJoin 数据。 如何先获取 forkJoin,然后获取主题数据? 任何帮助表示感谢...

angular rxjs fork-join subject
1个回答
0
投票

首先,当您使用异步实体时,无法保证在组件中获取数据的顺序。我会使用

BehaviorSubject
代替
Subject
来保证您从其他组件接收数据。

您的服务将是这样的:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SelectedClusterService {

  constructor() { }

  public readonly selectedClusterName = new BehaviorSubject<string | undefined>(undefined);

}

您的组件:

ngOnInit() {
    forkJoin([
      this.dataService.getUpgradeAppList(),
      this.dataService.getClusterList()
    ]).
    pipe(
      tap((data: any) => {
        console.log("forkJoin :: ngOnInit ::", data);
        this.appList = data[0].apps;
        this.clusterList = data[1];
      }),
      switchMap(() => this.selectedClusterService.selectedClusterName),
      filter(res => res !== undefined)
    ).subscribe(res => {
      this.selectedCluster = res;
      console.log("this.selectedCluster", this.selectedCluster);
    });     
  }

在您的

anotherComponent
中,您可以使用
switchMap
运算符开始从
oneComponent
接收数据,并使用
filter
忽略
BehaviorSubject
中我们设置为
undefined
的初始值。

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