Rxjs将字符串追加到一个可观察的?

时间:2018-01-28 22:02:30

标签: angular typescript rxjs angularfire2

我不确定这篇文章的标题应该是什么,因为我还不确定到底会有什么结果。我创建了一个简单的ngx图表(条形图),显示给定步骤中的帐户数量。我从Firestore中提取数据。它记录的帐户数量很好,但我还需要通过相应的步骤,这就是我被困的地方。数据的格式必须是名称,值对象的数组。这是我的代码。对此的任何帮助将不胜感激。

import { Account } from './../../../models/account.model';
import { ChartService } from './../../../services/chart.service';
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { map } from 'rxjs/operator/map';
import 'rxjs/add/observable/from';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/combineAll';

@Component({
  selector: 'app-steps-chart',
  templateUrl: './steps-chart.component.html',
  styleUrls: ['./steps-chart.component.css']
})
export class StepsChartComponent implements OnInit {
  steps = ['A', 'PA', 'PS', 'CI', 'CN'];
  steps$;
  chartData = [];
  count = 0;

  colorScheme = {
    domain: ['#03a9f4', '#009688', '#f29706', '#673ab7', '#f44336']
  };

  // options
  showXAxis = true;
  showYAxis = true;
  gradient = false;
  showLegend = true;
  showXAxisLabel = true;
  xAxisLabel = 'Steps';
  showYAxisLabel = true;
  yAxisLabel = 'Accounts';

  constructor(private chartService: ChartService) { }

  ngOnInit() {
    this.steps$ = Observable.from(this.steps);

    this.chartService.getAccounts().switchMap(() => {
      const accounts$ = this.steps$.map(step => {
        return this.chartService.getAccountsByStep(step);
      });
      const combined$ = accounts$.combineAll();
      return combined$;
    }).map(accounts => {
      console.log(accounts);
      return accounts.map(a => {
        return {
          'name': step, // need to figure out how to get step
          'value': a.length
        };
      });
    })
    .subscribe(data => {
      console.log(data);
    });
  }

}

1 个答案:

答案 0 :(得分:0)

你可以使用forkJoin并像这样重新组织:

// This is according to your comments in the code
const convertAccount = (account, step) => {
  return {
    name: step,
    value: account.length,
  };
};

// Gets the accounts for the given step and maps the result
// to the format we need for the chart.
const convertStep = step => this.chartService.getAccountsByStep(step)
  .map(accounts => accounts.map(account => convertAccount(account, step)));

Observable
  // Fire requests for all steps in parallel and wait for them
  // all to finish
  .forkJoin(...this.steps.map(convertStep))
  // Now we have an array of arrays, so flatten it out
  .map(([...data]) => data.reduce((a, b) => [...a, ...b], []))
  .subscribe(console.log)

我删除了对this.chartService.getAccounts()的调用,但似乎没有做任何事情。