使用BehaviorSubject将数据从一个组件发送到另一个组件

时间:2020-07-23 08:17:39

标签: angular

Bonjour

我正在从API检索数据,我希望在一个组件中检索到的数据被发送到另一个组件。 不幸的是,它们是同一级别的组件。

当我在接收数据的组件中创建一个.log控制台时,当前数据以这种形式到达:

++count

这是代码:

服务:

archivedGoodsSold: (2) [{…}, {…}]
archivedLeasedGoods: []
cheaperGoodsRented: (43) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}

要接收数据的组件:

  data = [];
  private paramSource = new BehaviorSubject(this.data);
  public sharedData = this.paramSource.asObservable();

  constructor(private apiClient: ApiClientService) {
  }

  getProducts() {
    return this.apiClient.get(this.apiUrl);
  }


  setData(data) {
    this.paramSource.next(data);
  }

应该发送数据的组件:

  data = [];
  constructor(dataMlsService: DataMlsService) {
    dataMlsService.sharedData.subscribe(data => this.data = data);
  }

  ngOnInit() {
    this.chartOptions = {
      chart: {
        type: 'spline'
      },
      title: false,
      xAxis: {

      },
      yAxis: {
        title: false,
      },
      legend: false,
      credits: {
        enabled: false
      },
      series: this.data,
    };
    console.log(this.data);
  }

我的问题是我没有在为此目的创建的组件中接收数据。

编辑: 当我在setData(data)方法中创建(data)的console.log时,我接收到数据。我认为我的问题是需要获取数据的组件

constructor(public dataMlsService: DataMlsService) { }

  ngOnInit() {
    this.dataMlsService.getProducts().subscribe((data) => {
      this.saleRentalInProgress = data['saleRentalInProgress'];
      this.newLeaseCompromises = data['newLeaseCompromises'];
      this.newOffersBookings = data['newOffersBookings'];
      this.newSoldLeased = data['newSoldLeased'];
      this.withdreawnGoods = data['withdreawnGoods'];
      this.cheaperGoodsSoldRented = data['cheaperGoodsSoldRented'];
      this.dataMlsService.setData(data);
    });
  }

编辑2:

现在数据到达正确的组件,但可以在构造函数中访问,而不能在ngOnInit()中访问

data = [];
  constructor(dataMlsService: DataMlsService) {
    dataMlsService.sharedData.subscribe(data => this.data = data);
  }

  ngOnInit() {
    console.log(this.data);

0 个答案:

没有答案