Querying data conditionally with Angular rxjs

I have a json file that contains multiple arrays structured like this:


{
    A[]
    B[]
    C[]
    ...
}

This is the query I am using:


myFunction():void{
this.apiService.getData()
.pipe(
  map((response: any) => response.A), // to access to the 'A' array
  take(1)
  )
.subscribe((records: MyType[]) => {
  this.records = records
});
}

The above query needs to be repeated for each array, with only the name of the array changing (e.g., from 'A' to 'B', 'C').

I am looking for a way to pass a variable to the function and implement a 'switch case' to handle redirection to the correct table.

I considered using the switchMap operator but it does not seem suitable in this scenario.

Any suggestions would be greatly appreciated!

Thank you

Answer №1

It seems to me that the problem can be addressed with a solution similar to the following:

function fetchRecords(data: string):void{
  this.apiService.getData()
  .pipe(
    map((response: any) => response[data]),
    // take(1) is not necessary if the apiService handles http requests appropriately
    )
  .subscribe((records: MyType[]) => {
    this.records = records
  });
}

Answer №2

This method appears to be functional, although I am uncertain if it is the optimal choice.


myFunction(prov: string): void{
    this.jsonService.getData()
      .pipe(
        map((response: any) => 
                prov === "A" ? response.A 
              : prov === "B" ? response.B 
              : prov === "C" ? response.C 
              : ...
              : response.Z
          )
        )
        .subscribe((record: any) =>
        this.records = records
      )
   }

Nevertheless, Picci's solution seems to be the simplest!

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

Exploring the world of interfaces in nested mapping functions

Currently, I'm faced with the challenge of mapping an array inside another map with an array. These are the specific interfaces that I am working with: interface Props { columns: Array<{field: string, headerName: string, width: number}>; row ...

Generate an array of identifiers from a pre-existing array

I am facing a challenge where I need to create an array of IDs for each element in an existing array whose size is unknown. The twist here is that every set of four elements should have the same ID. As an illustration, if the original array (let's ca ...

What methods are available to pass a variable value between two components in Angular 2?

I've been experimenting with Angular2 and recently created a component called appmenu using angular cli. The code in appmenu.html looks like this: <ul> <li (click)="menuitem1()">Menu Item 1</li> <li>Menu Item 2</li> ...

Tips for attaching an event listener to a div element that is accessed by reference in a React and TypeScript environment

I am attempting to attach an event listener to the div element using a ref. In my code, I have added a ref called div_ref to the Wrapper div and accessed that div_ref in the enableDragEventListeners method to add event listeners to it on component mount. ...

When a URL is triggered via a browser notification in Angular 2, the target component ceases to function properly

Whenever I access a URL by clicking on a browser notification, the functionality of the page seems to stop working. To demonstrate this issue, I have a small project available here: https://github.com/bdwbdv/quickstart Expected behavior: after starting t ...

Ways to determine if a date matches today's date within a component template

I am currently displaying a list of news articles on the webpage and I want to show the word "Today" if the news article's date is equal to today's date. Otherwise, I want to display the full date on the page. Is there a way to compare the news.D ...

Angular: Marking individuals in a FormArray as labels or flags

I need to distinguish some members (FormControl / FormGroup) within a FormArray by labeling or flagging them to group accordingly. For instance: A user can input values in three ways (uploading an Excel file, generating from a back-end service, or manua ...

Strange occurrences observed while looping through an enum in TypeScript

Just now, I came across this issue while attempting to loop through an enum. Imagine you have the following: enum Gender { Male = 1, Female = 2 } If you write: for (let gender in Gender) { console.log(gender) } You will notice that it iter ...

Encountered Angular SSR Serve Error: NullInjectorError - StaticInjectorError in AppServerModule with the following reference:

While working on building an application with Angular's SSR and serving it, I encountered a specific error. All services and components have been properly injected. Error: ERROR Error [NullInjectorError]: StaticInjectorError(AppServerModule)[REQUEST] ...

How to Make an HTTP POST Request in Angular without Including Headers

How can I configure Angular (version 4.0.2) to send a minimal HTTP POST request? When I use the default code like this: import { Http, Response } from '@angular/http'; export class MyService { constructor(public http: Http) { this.http.pos ...

Is there a method of converting React components into strings for manipulation?

In my React TypeScript project, I am utilizing a crucial library that contains a component which transforms text into SVG. Let's refer to this library component as <LibraryRenderer />. To enhance the functionality, I have enclosed this componen ...

An error occurred while running React, Next.js, and Type Script: Unhandled Runtime Error - TypeError: Unable to access 'value' property of undefined

I have been working on a multi-page form and using the antd package to add some styling to it. On the main page of the form, I implemented the following code (making sure I imported everything required). export class CreateNewContract extends Component ...

Open new tab for Angular OAuth2 OIDC login process

Currently, I am incorporating the authorization code flow using angular-oauth2-oidc in my Angular application. It is a fairly straightforward process. However, I would like to have the ability for the login flow to open in a new tab when the login button ...

Hiding a div after three clicks using HTML

What is the best way to hide a div tag containing an input tag after clicking on the input tag three times using HTML and angular? ...

Angular findIndex troubleshooting: solutions and tips

INFORMATION = { code: 'no1', name: 'Room 1', room: { id: 'num1', class: 'school 1' } }; DATABASE = [{ code: 'no1', name: 'Room 1', room: { id: 'num1', ...

The application of Angular's extension may experience functionality issues due to a failed ngcc operation

https://i.stack.imgur.com/Q7eFX.png The current issue I am encountering. https://i.stack.imgur.com/Kj1r0.png However, the command ng serve is functioning smoothly without any errors. https://i.stack.imgur.com/0SluL.png I'm also facing this partic ...

Angular issue: Unable to scroll to top after route change and loading a new component

In the process of developing a simple Angular application, I encountered an issue. When navigating from my home page to the services page, scrolling down, and then returning to the home page, the scroll position is always set to the bottom of the page. My ...

How to Position Logo in the Center of MUI AppBar in React

I've been struggling to center align the logo in the AppBar. I can't seem to get the logo to be centered both vertically and horizontally on its own. Here is my code from AppBar.tsx: import * as React from 'react'; import { styled, useT ...

Referring to a component type causes a cycle of dependencies

I have a unique situation where I am using a single service to open multiple dialogs, some of which can trigger other dialogs through the same service. The dynamic dialog service from PrimeNg is being used to open a dialog component by Type<any>. Ho ...

Android causing multiple triggerings of pause and resume events in Ionic 3

Encountering a peculiar problem with the Ionic 3 pause and resume events. Every time I pause the application, the events trigger multiple times (2, 3 times, etc). Here is the snippet of code: this.platform.ready().then(() => { this.platform.pause.sub ...