How can I add a string to an observable using Rxjs?

Uncertain about what title to give this post, as I'm still figuring out the goal. Working on a simple ngx chart (bar graph) to show the number of accounts in each step, sourced from Firestore. It's logging account numbers correctly, but struggling with passing the corresponding step. Data format needs to be an array of name, value pairs. Here's my code - any assistance is welcome.

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);
    });
  }

}

Answer №1

To optimize the code, consider using forkJoin and restructuring it like so:

// Adjusting based on comments within the code
const convertAccount = (account, step) => {
  return {
    name: step,
    value: account.length,
  };
};

// Retrieve accounts for the specified step and reformat them for the chart
const convertStep = step => this.chartService.getAccountsByStep(step)
  .map(accounts => accounts.map(account => convertAccount(account, step)));

Observable
  // Send requests for all steps concurrently and wait for completion
  .forkJoin(...this.steps.map(convertStep))
  // Flattening out the array of arrays generated by forkJoin
  .map(([...data]) => data.reduce((a, b) => [...a, ...b], []))
  .subscribe(console.log)

The unnecessary call to this.chartService.getAccounts() has been removed as it does not appear to serve any purpose.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When accessing APIs, create an array of observables for each user call and then trigger a function once all are successfully resolved

As I aim to generate a list of observables while a user engages with the webpage, I am faced with the challenge of individually subscribing to each observable, but desiring another function to execute after individual or multiple simultaneous API calls are ...

Watching for when the state changes in the AngularJS framework using the `$scope.$on('$stateChangeStart')` and

My AngularJs application has the functionality to detect a change in state (using ui.router) and prompt the user to save any unsaved changes. Currently, I am utilizing a confirm dialog for this task: $scope.$on('$stateChangeStart', () => { ...

Changing a JSON string into an object and linking it to an HTML select element in Angular 2

I have received a response from my service that I want to bind to an HTML select dropdown. However, the response appears to be in string format rather than an array. "{"Codes":{ "CountryCodes": [ { "Code": "002", "Desc": "AFGHANISTAN" ...

Troubleshooting Angular HTTP: Issue with the HTTP request headers not updating

// assigning the httpclient protected _http: HttpClient = inject(HttpClient); // defining the options for the request const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/tcc' }), observe: 'resp ...

The context value is lagging behind and not updating promptly

context.tsx import { PropsWithChildren, createContext, useContext, useState } from "react"; import auth_svc from "../services/authServices"; import { Result, message } from "antd"; interface Result { _id: String | null; f ...

When utilizing the catch function callback in Angular 2 with RxJs, the binding to 'this' can trigger the HTTP request to loop repeatedly

I have developed a method to handle errors resulting from http requests. Here is an example of how it functions: public handleError(err: any, caught: Observable<any>): Observable<any> { //irrelevant code omitted this.logger.debug(err);//e ...

What causes the Angular router URL to vary from the document location on reload while employing CanActivate?

My Angular 2 router setup seems to be causing some issues. When I refresh the page, I've noticed that the router object's URL value is different from the location.hash property of the document. For example, when I check router.url, I get "/", bu ...

The object may be null

Is there a way to verify if an object is null? let hostels = null; if (hostels[0] !== null && hostels[0].name !== null) { } However, I encountered the following error: error TS2531: Object is possibly 'null'. ...

Ways to resolve the issue of "Property 'tenant' does not exist on type"

I have a request and I have exported this json body. export const settingsReq = { "states": [ { "initial": false, "style": "plain", "elements": [ { "type" ...

Having trouble with Angular 2's Output/emit() function not functioning properly

Struggling to understand why I am unable to send or receive some data. The toggleNavigation() function is triggering, but unsure if the .emit() method is actually functioning as intended. My end goal is to collapse and expand the navigation menu, but for ...

Error message is displayed on the datepicker only when it loses focus

I have implemented a material datepicker in my project, using the following resource: https://material.angular.io/components/datepicker/overview. As part of the datepicker, I have a custom async validator that makes API calls for validation purposes. The ...

TypeScript fails to acknowledge an exported enum

Currently utilizing TypeScript version 2.5.3 along with Angular 5. I have an enum defined in a separate file as follows: export enum eUserType { Driver = 1, Passenger = 2, User = 3 } To import and use it in another ts file, I do the following: i ...

Tips for commenting HTML in React components when using TypeScript

class MyClass extends React.Component<any, any> { render(): JSX.Element { return (<div> /*<div>{this.state.myVal} This isn't working</div>*/ ///<div>{this.state.myVal} This isn't w ...

A guide to showcasing data within PrimeNG's pie chart component using either JavaScript or Angular

I have utilized the pie chart feature from the PRIMENG CHART PLUGIN My goal is to showcase the values within a pie chart Below, you can find my code for reference **Within app.component.html** <div style="display: block"> <p-chart type="pi ...

Difficulty in loading TypeScript web component using Polymer serve

As I follow the LitElement guide provided here: , I meticulously adhere to each step mentioned and then execute polymer serve in my project's root directory. I diligently clone every file from their example stackblitz pages. Is it possible that using ...

Can you explain the significance of the angle-bracket notation in Typescript?

Typescript confuses me with this syntax: myFunc<MyType>(myObject) Can someone clarify what this means? I know that <MyType>myObject is a type-assertion, but when it's placed between the function name and the open parenthesis, I'm lo ...

Verify in typescript if type A is equal to either type B or type C

Within one specific file, there is a structured code block like the following: export const _total = { a: '', b: '', c: '', d: '', e: '', f: '', } type TotalKeysType = typeof _all; ex ...

Testing an Angular component using Jasmine within a project with multiple module files

Struggling to troubleshoot an issue I'm facing with my testing setup. The service tests that rely solely on the httpclient are running smoothly. However, when attempting to test a component with dependencies, errors start popping up without even execu ...

Navigating with Angular's routerLink to specific paths allows for

My goal is to access localhost:4200/route/SOME_PARAMETER, with SOME_PARAMETER representing a component property. My current code snippet looks like this: <a [routerLink]="['/route/${SOME_PARAMETER}']"> However, it seems to be ...

Tips for maintaining a custom length for matpaginator

I have implemented a MatPaginator with a custom length, but I am facing an issue. Initially, the custom length works fine. However, when I make additional API requests using a search input field and receive new results, the paginator reverts back to the de ...